我必须将更新后的字典数据附加到下面程序的列表中。
hello = ["hello ", "cruel "]
hi = ["hi", "world"]
myli = []
mydict = {}
def abc():
for i in xrange(len(hello)):
for j in xrange(len(hi)):
mydict["Mydata"] = str(j)
myli.append( [hello[i], hi[j], mydict])
abc()
print myli
但结果是
[['hello ', 'hi', {'Mydata': '1'}], ['hello ', 'world', {'Mydata': '1'}], ['cruel ', 'hi', {'Mydata': '1'}], ['cruel ', 'world', {'Mydata': '1'}]]
,正如我所期望的那样,
[['hello ', 'hi', {'Mydata': '0'}], ['hello ', 'world', {'Mydata': '1'}], ['cruel ', 'hi', {'Mydata': '0'}], ['cruel ', 'world', {'Mydata': '1'}]]
我不明白我错在哪里?
最佳答案
不是每次都创建一个新的dict,而是覆盖one dictmydict
中的值。只需为每个列表创建一个新的dict:
def abc(hello, hi):
myli = []
for i in xrange(len(hello)):
for j in xrange(len(hi)):
myli.append([hello[i], hi[j], {"Mydata": str(j)}])
return myli
hello = ["hello ", "cruel "]
hi = ["hi", "world"]
print abc(hello, hi)