【问题标题】:editing a list in a different file在不同的文件中编辑列表
【发布时间】:2023-01-30 06:30:48
【问题描述】:

我正在尝试在 python django 的不同文件中编辑列表。我有一个名为 models.py 的文件和一个名为 details.py 的文件,

细节.py:

DATA = [
{'height': '184', 'width': '49'},
{'height': '161', 'width': '31'},
{'height': '197', 'width': '25'},
{'height': '123', 'width': '56'},
{'height': '152', 'width': '24'},
{'height': '177', 'width': '27'},
 ]

def edit_list(h,w):
    for info in DATA:
        if info['height'] == h:
           info['width'] = w
    return True
models.py:

from abc.details import edit_list

height = '161'
new_width = '52' 
update_data = edit_list(height, new_width) #this doesn't work, when I check the file nothing changes in the list :/

使这成为可能的最佳方法是什么?

(我不想将此列表导入数据库并只更新那里的宽度,我希望宽度在文件本身内部更新,删除 details.py 文件并在无法进行编辑时使用 python 创建一个新文件因为很少有其他函数也一直从列表中获取数据。

【问题讨论】:

    标签: python django list


    【解决方案1】:

    你需要缩进你的语句 info['width'] = w,否则你不会得到你期望的结果。更重要的是,您需要“取消缩进”您的退货声明。目前,您在执行 for 语句中的第一行后从函数返回。其余行永远不会执行。

    def edit_list(h,w):
        for info in DATA:
            if info['height'] == h:
                info['width'] = w
        return True
    

    要将 DATA 用作全局变量并因此能够更改其值,您需要将 details.py 更改为:

    DATA = [
    {'height': '184', 'width': '49'},
    {'height': '161', 'width': '31'},
    {'height': '197', 'width': '25'},
    {'height': '123', 'width': '56'},
    {'height': '152', 'width': '24'},
    {'height': '177', 'width': '27'},
     ]
    
    
    def edit_list(h,w):
        global DATA
    
        for info in DATA:
            if info['height'] == h:
                info['width'] = w
        return True
    

    【讨论】:

    • 由于某种原因,它没有正确显示,当然我让它正确缩进,否则它无论如何都会导致问题..但这并没有回答我的问题:数据没有更新......
    • 在那种情况下我不知道。这个对我有用。我所做的唯一更改是你的导入语句'from abc.details import edit_list'我有'from details import edit_list,DATA'。我只添加了 DATA 以便能够打印它并且它有效。行 {'height': '161', 'width': '31'} 变成了 {'height': '161', 'width': '52'}。我假设你有 abc.detail 因为你有不同的文件结构。我怀疑您没有正确获取 details.py 的路径。尝试将它放在与模型相同的文件夹中,并使用与我相同的导入。
    • 我可以毫无问题地从列表中获取数据,但是如果我想更新该列表,它就不起作用了。糟糕,我认为这可能是权限问题?..因为它在不同的文件夹中?我现在当然可以移动它进行测试,但我不能保持它的结构,因为许多其他函数依赖于它并从 modelname.filename.py 调用它
    • 我也在 python manage.py shell 中尝试过它没有更新,我可以很好地获取数据但我不能写任何东西并将它保存到那个列表中。
    • 你在做记忆的改变吗?或者您是否检查过列表确实在那里更新的文件本身?
    猜你喜欢
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-01
    • 1970-01-01
    • 2011-05-14
    相关资源
    最近更新 更多