在while循环中计算输入?

时间:2013-03-11 22:38:53

标签: python string python-3.x while-loop counter

我需要帮助我必须编写一个函数,其中包含一个while循环,它将继续运行直到用户输入空输入,一旦发生这种情况,该函数将返回一个名字输入的次数

到目前为止,我的代码是:

while True:
    name = input('Enter a name:')

    lst = name.split()
    count={}
    for n in lst:
        if n in count:
            count[n]+=1

    for n in count:
        if count[n] == 1:
            print('There is {} student named {}'.format(count[n],\
                                                    n))
        else:

            print('There are {} students named {}'.format(count[n],\
                                                        n))

这不重复它只询问用户一次并返回1

输出应如下所示:

Enter next name:Bob
Enter next name:Mike
Enter next name:Bob
Enter next name:Sam
Enter next name:Mike
Enter next name:Bob
Enter next name:

There is 1 student named Sam
There are 2 students named Mike
There are 3 students named Bob

4 个答案:

答案 0 :(得分:1)

    for n in lst:
        if n in count:
            count[n]+=1

在上面的代码中,n从未添加到您的count字典中。即循环后count仍为空..

答案 1 :(得分:1)

@zzk说的是

for n in lst:
    if n in count:
        count[n]+=1
    else:
        count[n]=1

使用每个人的建议来获得最有效的答案

count= {}

while True:

    name = raw_input('Enter a name:')
    lst = name.split()

    for n in lst:
        count[n] = count.get(n, 0) + 1

    if not lst:
        for n in count:
            if count[n] == 1:
                print('There is {} student named {}'.format(count[n],n))
            else:
                print('There are {} students named {}'.format(count[n],n))
        break

答案 2 :(得分:1)

除了您永远不会将n添加到count字典之外,您可以在while循环的每次迭代中反复初始化此字典。你必须把它放在循环之外。

count= {}

while True:
    name = input('Enter a name:')

    lst = name.split()
    for n in lst:
        if n in count:
            count[n] += 1
        else:
            count[n] = 1

    for n in count:
        if count[n] == 1:
            print('There is {} student named {}'.format(count[n],\
                                                    n))
        else:

            print('There are {} students named {}'.format(count[n],\
                                                        n))

答案 3 :(得分:1)

以下有点矫枉过正。这只是要知道有标准模块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)

可以删除部分代码。 name中的enterStudents()参数允许调用函数以向现有集合添加名称。 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