首页 > 解决方案 > Python 3 列表的意外修改

问题描述

我是编码新手,正在尝试解决之前提出的问题。有一个字典列表(lst)。想要创建一个新的字典列表(newlist),其中原始列表中相同字典的计数,在新列表中作为每个字典中的键项。我下面的代码将字典的数量添加到原始列表的字典中,我不明白为什么。

lst = [{'time': 10, 'stuff': 'abcd'},{'time': 10, 'stuff':'abcd'},{'time': 11, 'stuff': 'bcd'},{'time': 12, 'stuff': 'dc'},{'time': 13, 'stuff': 'ak'},{'time': 11, 'stuff': 'bcd'}]
newlist= []
m = 0
while len(lst)>0 :
    y = lst[0]
    ycount = lst.count(y)
    newlist=newlist + [y]
    newlist[m]['count'] = ycount
    print(f'lst = {lst}\n')
    while y in lst:
        lst.remove(y)
    m += 1
print(f'newlist= {newlist}')

标签: pythonlistdictionary

解决方案


推荐阅读