python - 为什么列表没有将字典数据附加到我的列表中?

标签 python dictionary

我必须将更新的字典数据附加到下面程序的列表中。

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/

相关文章:

python - 如何从我的 setup.py 文件中使用 Cython 进行外部模块编译?

python - 如何在没有 GUI 的情况下使用 PyQt?

来自 Firebase 的 Swift 4 展开字典

arrays - 返回数值 0 或 1 表示真或假的 map 函数

python - 在 Windows 上使用 git-remote-hg

python - sys.stdin.readline() 与 if else (Python)

python - Tensorflow:如何使用dynamic_rnn从LSTMCell获取中间细胞状态(c)?

python - 将 Dataframe 转换为具有列表值的字典

algorithm - 有单词流行度的词典?

java - java中如何从Map键中获取值