计算python中列表中的名称数量

时间:2017-09-08 14:00:00

标签: python

我有一个名单中有一个名单:

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

使用set i获取uniquenames,因此唯一名称位于不同的列表中

但现在我想计算每个测试的名称数量:2 hallo:1

我有这个:

for i in range(len(uniquenames)):
    countname = name.count[i]

但它给了我这个错误: TypeError:'builtin_function_or_method'对象不可订阅

我该如何解决?

2 个答案:

答案 0 :(得分:2)

你可以使用字典:

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

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

如果您想使其不区分大小写,请使用:

names = ['test','hallo','test', 'HaLLo', 'tESt']
countnames = {}
for name in names:
    name = name.lower() # => to make 'test' and 'Test' and 'TeST'...etc the same
    if name in countnames:
        countnames[name] += 1
    else:
        countnames[name] = 1

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

如果您希望键是计数,请使用数组将名称存储在:

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

答案 1 :(得分:1)

使用Counter中的collections

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

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