以下是有点矫枉过正。这只是要知道有标准模块collections
,它包含Counter
类。无论如何,我更喜欢问题中使用的简单解决方案(在删除错误之后)。第一个函数读取输入并在输入空名称时中断。第二个函数显示结果:
#!python3
import collections
def enterStudents(names=None):
# Initialize the collection of counted names if it was not passed
# as the argument.
if names is None:
names = collections.Counter()
# Ask for names until the empty input.
while True:
name = input('Enter a name: ')
# Users are beasts. They may enter whitespaces.
# Strip it first and if the result is empty string, break the loop.
name = name.strip()
if len(name) == 0:
break
# The alternative is to split the given string to the first
# name and the other names. In the case, the strip is done
# automatically. The end-of-the-loop test can be based
# on testing the list.
#
# lst = name.split()
# if not lst:
# break
#
# name = lst[0]
# (my thanks to johnthexiii ;)
# New name entered -- update the collection. The update
# uses the argument as iterable and adds the elements. Because
# of this the name must be wrapped in a list (or some other
# iterable container). Otherwise, the letters of the name would
# be added to the collection.
#
# The collections.Counter() can be considered a bit overkill.
# Anyway, it may be handy in more complex cases.
names.update([name])
# Return the collection of counted names.
return names
def printStudents(names):
print(names) # just for debugging
# Use .most_common() without the integer argument to iterate over
# all elements of the collection.
for name, cnt in names.most_common():
if cnt == 1:
print('There is one student named', name)
else:
print('There are {} students named {}'.format(cnt, name))
# The body of a program.
if __name__ == '__main__':
names = enterStudents()
printStudents(names)
有部分代码可以删除。 enterStudents()
中的name
参数允许调用该函数为现有集合添加名称。初始化为None
用于将空初始集合作为默认集合。
如果要收集包括空格在内的所有内容,则name.strip()
不是必需的。
它打印出我的控制台上
c:\tmp\___python\user\so15350021>py a.py
Enter a name: a
Enter a name: b
Enter a name: c
Enter a name: a
Enter a name: a
Enter a name: a
Enter a name:
Counter({'a': 4, 'b': 1, 'c': 1})
There are 4 students named a
There is one student named b
There is one student named c
实际上,它会在第一个'+ = 1'和'KeyError'失败。这是因为'n'没有任何价值。 – pepr 2013-03-12 12:45:13
@pepr no。 'count [n] + = 1'不会被执行,因为'n in count'是'False' – zzk 2013-03-12 18:14:30
+1。你是对的 – pepr 2013-03-13 07:40:59