计算重复字典,然后附加一个count键,它的值为

2024-06-28 19:47:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份字典清单:

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'}

Tags: 项目nameinpytxt列表pngcount
3条回答

你可以用groupby这样做

In [76]: from itertools import groupby
In [77]: data = []
In [78]: for g,l in groupby(sorted(flist)):
    ...:     g.update({'count':len(list(l))})
    ...:     data.append(g)
    ...:     

In [79]: print data
Out[79]: 
[{'count': 1, 'ext': '.png', 'name': 'picture1'},
 {'count': 1, 'ext': '.py', 'name': 'script'},
 {'count': 2, 'ext': '.txt', 'name': 'file1'}]

在对原始列表排序之后,可以使用groupby。你知道吗

l = sorted(flist, key=lambda item: item["ext"])

summary = []

for key, value in groupby(l):
    key.update({"count": len(list(value))})
    summary.append(key)

两个问题。你知道吗

1)item in summary-您正在使用计数编辑来自flistitem,因此原始项不再存在。你知道吗

2)只追加初始值,不追加和

item['count'] = 1
summary.append(item)

您可能对Counter对象感兴趣

from collections import Counter, namedtuple
File = namedtuple('File', ['name', 'ext'])

flist = [
  File('file1', '.txt'),
  File('picture1', 'png'),
  File('file1', '.txt'),
  File('script', '.py')
  ]

c = Counter()
for f in flist:
  c[f] += 1

for f, count in c.items():
  print(count, f)

输出

2 File(name='file1', ext='.txt')
1 File(name='picture1', ext='png')
1 File(name='script', ext='.py')

相关问题 更多 >