我正在尝试编写一个不接受输入的函数,而是要求输入一个名称。如果输入空字符串,则该函数应为每个名称打印具有相同名称的人数。
例如:
>>>name()
Enter a name: Paul
Enter a name: Bill
Enter a name: John
Enter a name: Paul
Enter a name: Nick
Enter a name: Bill
Enter a name: Bill
Enter a name:
There is 1 person named John
There is 1 person named Nick
There are 2 people named Paul
There are 3 people named Bill
到目前为止,我有:
def name():
name = input ('Enter a name: ')
count = 0
while name:
if name == input ('Enter a name: '):
count = count + 1
else:
print (count)
我很确定我没有正确计算。 你怎么能正确地完成这个功能呢?当你不知道有多少不同的名字时,你如何区分不同的输入并计算它们?
另外,如果可能的话,即使效率不高,我仍然希望学习基本代码。
答案 0 :(得分:4)
只是为了一个单行的乐趣:
>>> collections.Counter(iter(functools.partial(input, "Enter a name: "), ""))
Enter a name: Paul
Enter a name: Bill
Enter a name: John
Enter a name: Paul
Enter a name: Nick
Enter a name: Bill
Enter a name: Bill
Enter a name:
Counter({'Bill': 3, 'Paul': 2, 'Nick': 1, 'John': 1})
这可能不是在实际代码中执行此操作的方法。
答案 1 :(得分:3)
from collections import defaultdict
dic = defaultdict(int)
while True:
name = input ('Enter a name: ')
if name:
dic[name] += 1
else:
for k,v in sorted(dic.items(), key = lambda x: (x[1],x[0])):
print ("There is {} person named {}".format(v,k))
break
演示:
$ python3 so.py
Enter a name: Paul
Enter a name: Bill
Enter a name: John
Enter a name: Paul
Enter a name: Nick
Enter a name: Bill
Enter a name: Bill
Enter a name:
There is 1 person named John
There is 1 person named Nick
There is 2 person named Paul
There is 3 person named Bill
答案 2 :(得分:3)
Python附带了一个专门用于计数的集合,名为Counter
。
import collections
counts = collections.Counter()
while True:
name = input('Enter a name: ')
if not name:
break
counts[name] += 1
for name, count in counts.items():
print('There is {} person named {}'.format(count, name))
如果您希望结果的顺序从最不常见到最常见,Counter
有一个按计数排序的函数most_common
。不幸的是,它是向后的...但你可以通过调用reversed
:
for name, count in reversed(counts.most_common()):
print('There is {} person named {}'.format(count, name))
或者,如果您更喜欢按名称排序:
for name, count in sorted(counts.items()):
print('There is {} person named {}'.format(count, name))
答案 3 :(得分:1)
你可以使用一个简单的python地图。这个功能:
names = {}
while True:
name = raw_input('Enter a name: ')
if not name:
break
if name not in names:
names[name] = 0
names[name] = names[name] + 1
for name in sorted(names, key=names.get):
if names[name] < 2:
print 'There is %d person named %s' % (names[name], name)
else:
print 'There are %d people named %s' % (names[name], name)