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']}
从
collections
使用Counter
:另外,为了使您的示例正常工作,您应该将
names.count[i]
更改为names.count(i)
,因为count
是一个函数。在你可以使用字典:
如果要使其不区分大小写,请使用以下命令:
^{pr2}$如果要将密钥作为计数,请使用数组将名称存储在:
相关问题 更多 >
编程相关推荐