1

我正在尝试编写一个不接受输入但要求输入名称的函数。如果您输入一个空字符串,该函数应该为每个名字打印同名的人数。

例如:

>>>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)

我很确定我没有正确计算。您将如何正确执行此功能,以及当您不知道将有多少不同名称时,如何区分不同的输入并计算它们?

另外,如果可能的话,我想在我仍在学习的时候使用基本代码,即使它效率不高。

4

4 回答 4

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

这可能不是在实际代码中执行此操作的方法。

于 2013-06-09T15:16:48.537 回答
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))
于 2013-06-09T15:31:15.433 回答
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
于 2013-06-09T15:13:26.940 回答
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)
于 2013-06-09T16:06:55.323 回答