0

ユーザーが空の入力を入力するまで継続する 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 回だけ尋ねて 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

4 に答える 4

1

nディクショナリに追加しないという事実を除いて、countwhileループを繰り返すたびにこのディクショナリを何度も初期化します。あなたはそれをループの外に置く必要があります。

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))
于 2013-03-12T12:19:15.020 に答える
1
    for n in lst:
        if n in count:
            count[n]+=1

上記のコードでは、 dictnに追加されることはありません。countつまりcount、ループの後もまだ空です。

于 2013-03-11T22:45:53.180 に答える
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
于 2013-03-12T12:13:47.730 に答える
1

以下は少しやり過ぎです。これは、標準モジュールがあり、そこにクラスcollectionsが含まれていることを知っているだけです。Counterとにかく、質問で使用されている単純な解決策を好みます(エラーを削除した後)。最初の関数は入力を読み取り、空の名前が入力されると中断します。2 番目の関数は結果を表示します。

#!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()により、関数を呼び出して既存のコレクションに名前を追加できます。初期化 toNoneは、空の初期コレクションをデフォルトのコレクションにするために使用されます。

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    
于 2013-03-12T13:22:56.303 に答える