I created a list called database and appended 'person' to it. When the values in person change from the for loop it keeps changing the values inside the array as well. The last value in 'reader_data' ends up being repeating 'row' times. I'd like to know why this happens and how can I prevent it from changing.
我创建了一个名为DATABASE的列表,并在其后面附加了‘Person’。当Person中的值从for循环更改时,它也会不断更改数组中的值。‘READER_DATA’中的最后一个值以重复‘ROW’次结束。我想知道为什么会发生这种情况,我怎样才能防止它改变。
with open(sys.argv[1]) as data_file:
reader_data = csv.reader(data_file)
headers = next(reader_data)
database = []
person = {}
for row in reader_data:
for i, value in list(enumerate(row)):
print(database)
if (i == 0):
person[headers[i]] = value
else:
person[headers[i]] = int(value)
database.append(person)
print(database)
更多回答
优秀答案推荐
Your database
list has many references to the same person
dictionary. To avoid this, append unique dictionaries by creating the person
variable within the first loop. Note also that variables declared within a with/as block are not locally scoped to that block. This means the rest of your code can unindent a level.
您的数据库列表有许多对同一人词典的引用。要避免这种情况,可以通过在第一个循环中创建Person变量来附加唯一词典。还要注意,在WITH/AS块中声明的变量并不是该块的本地作用域。这意味着您的代码的其余部分可以不缩进一个级别。
with open(sys.argv[1]) as data_file:
reader_data = csv.reader(data_file)
headers = next(reader_data)
database = []
for row in reader_data:
person = {}
for i, value in list(enumerate(row)):
print(database)
if (i == 0):
person[headers[i]] = value
else:
person[headers[i]] = int(value)
database.append(person)
print(database)
If you didn't need the print
within the loop, you could express the construction of database
with list and dictionary comprehensions.
如果你不需要在循环中打印,你可以用列表和字典理解来表达数据库的构造。
database = [
{
headers[i]: (value if i == 0 else int(value))
for i, value in enumerate(row)
}
for row in reader_data
]
更多回答
Feel free to accept the answer if you feel it's answered your question.
如果你觉得答案已经回答了你的问题,请随意接受。
Please help to keep the site organized by helping to close obviously duplicate questions as duplicates. This is one of the most common Python "gotchas".
请帮助保持网站组织帮助关闭明显重复的问题重复.这是最常见的Python“陷阱”之一。
我是一名优秀的程序员,十分优秀!