在python中统计列表中的名称数

2024-09-25 16:31:31 发布

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

我有一张单子上面有名字:

names = ['test','hallo','test']
uniquenames = ['test','hallo']

有了set,我得到了uniquenames,所以唯一的名称在不同的列表中

但现在我想数一数每个这样的名字有多少测试:2哈罗:1个

我有这个:

^{pr2}$

但它给了我一个错误: TypeError:“内置函数”或“方法”对象不可订阅

我该怎么解决呢?在


Tags: 方法函数test名称列表names错误名字
2条回答

collections使用Counter

>>> from collections import Counter
>>> Counter(names)
Counter({'test': 2, 'hallo': 1})

另外,为了使您的示例正常工作,您应该将names.count[i]更改为names.count(i),因为count是一个函数。在

你可以使用字典:

names = ['test','hallo','test']
countnames = {}
for name in names:
    if name in countnames:
        countnames[name] += 1
    else:
        countnames[name] = 1

print(countnames) # => {'test': 2, 'hallo': 1}

如果要使其不区分大小写,请使用以下命令:

^{pr2}$

如果要将密钥作为计数,请使用数组将名称存储在:

names = ['test','hallo','test','name', 'HaLLo', 'tESt','name', 'Hi', 'hi', 'Name', 'once']
temp = {}
for name in names:
    name = name.lower()
    if name in temp:
        temp[name] += 1
    else:
        temp[name] = 1
countnames = {}
for key, value in temp.items():
    if value in countnames:
        countnames[value].append(key)
    else:
        countnames[value] = [key]
print(countnames) # => {3: ['test', 'name'], 2: ['hallo', 'hi'], 1: ['once']}

相关问题 更多 >