python - 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}')
解决方案
推荐阅读
- python - Python 正则表达式在前两个空格之间找到一个单词
- hyperledger-fabric - Hyperledger Fabric 硬件要求
- django - Django Rest Framework:在模型字段中设置“验证器”时验证不起作用
- node.js - 为普通打字稿函数调用 Mocha 根级别之前并引发错误为“ReferenceError:未定义之前”
- openlayers - 地图和总览图可以拆分成两个html吗?
- r - 如何从 R 中的表中创建正确分段的列表?
- node.js - 什么是错误当使用 service worker 和 web-push 时,脚本在 vuejs 和 nodejs 中具有不受支持的 MIME 类型('text/html')
- node.js - RSA_padding_check_PKCS1_type_2:pkcs解码错误
- c# - 部分类型推断可能吗?
- spring - @Cacheable 创建的缓存的单独设置