我有一份字典清单:
flist = [
{'ext' : '.txt', 'name' : 'file1'},
{'ext' : '.png', 'name' : 'picture1'},
{'ext' : '.txt', 'name' : 'file1'},
{'ext' : '.py', 'name' : 'script'},
]
我想创建一个新的列表,其中有多少次的项目出现在第一个列表计数。你知道吗
summary = []
for item in flist:
if item not in summary:
item['count'] = 1
summary.append(item)
else:
item['count'] += 1
for i in summary:
print i
我希望输出列表如下所示:
{'count': 2, 'ext': '.txt', 'name': 'file1'}
{'count': 1, 'ext': '.png', 'name': 'picture1'}
{'count': 1, 'ext': '.py', 'name': 'script'}
但最终的结果是,我得到了所有4个项目,“计数:1”。我假设是因为它第一次增加了count:1,这使得dict是唯一的。你知道吗
{'count': 1, 'ext': '.txt', 'name': 'file1'}
{'count': 1, 'ext': '.png', 'name': 'picture1'}
{'count': 1, 'ext': '.txt', 'name': 'file1'}
{'count': 1, 'ext': '.py', 'name': 'script'}
你可以用
groupby
这样做在对原始列表排序之后,可以使用
groupby
。你知道吗两个问题。你知道吗
1)
item in summary
-您正在使用计数编辑来自flist
的item
,因此原始项不再存在。你知道吗2)只追加初始值,不追加和
您可能对
Counter
对象感兴趣输出
相关问题 更多 >
编程相关推荐