这里我想在嵌套列表的字典中插入一个值。 这就是我的尝试,
company_ids = [1,2,3]
seller_ids = [[0, False, { u'company_id': 4}]]
result = []
for company in company_ids:
for i in xrange(0, len(seller_ids)):
seller_ids[i][2]['company_id'] = company
result.append(seller_ids[i])
print result
我收到了这个
[[0, False, {u'company_id': 3}], [0, False, {u'company_id': 3}], [0, False, {u'company_id': 3}]]
但我期待这一点,
[[0, False, {u'company_id': 1}], [0, False, {u'company_id': 2}], [0, False, {u'company_id': 3}]]
请帮我解决这个问题。提前谢谢......
答案 0 :(得分:2)
您需要在seller_ids中创建要更改的条目的副本。就像niemmi说的那样,否则你每次都操纵相同的条目。
from copy import deepcopy
company_ids = [1,2,3]
seller_ids = [[0, False, { u'company_id': 4}]]
result = []
for company in company_ids:
for i in xrange(0, len(seller_ids)):
mycopy = deepcopy(seller_ids[i])
mycopy[2]['company_id'] = company
result.append(mycopy)
print result
答案 1 :(得分:1)
发生这种情况是因为您每次更改并附加相同的列表[0, False, { u'company_id': 4}]
到result
,所以最后它将包含对最新修改的同一列表的三个引用。