我必须将更新的字典数据附加到下面程序的列表中。
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'}], ['残酷', ' hi', {'Mydata': '1'}], ['残酷', '世界', {'Mydata': '1'}]]
,
正如我期望的输出一样,
[['hello', 'hi', {'Mydata': '0'}], ['hello', 'world', {'Mydata': '1'}], ['残酷', ' hi', {'Mydata': '0'}], ['残酷', '世界', {'Mydata': '1'}]]
我不明白我哪里出了问题?
最佳答案
您不会每次都创建一个新的字典,而是覆盖一个字典mydict
中的值。只需为每个列表创建一个新字典即可:
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)
关于python - 为什么列表没有将字典数据附加到我的列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35444075/