2013-03-11 134 views
0

我需要一個功能我必須寫,其中包括一個while循環將繼續下去,直到用戶輸入一個空的輸入,一旦出現這種情況,該函數將返回一個名稱已進入在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 

回答

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

在上述代碼中,n永遠不會添加到您的count字典中。即count仍然在循環後空..

+0

實際上,它會在第一個'+ = 1'和'KeyError'失敗。這是因爲'n'沒有任何價值。 – pepr 2013-03-12 12:45:13

+1

@pepr no。 'count [n] + = 1'不會被執行,因爲'n in count'是'False' – zzk 2013-03-12 18:14:30

+0

+1。你是對的 – pepr 2013-03-13 07:40:59

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 
+0

'if'下面的四行可以用'count [n] = count.get(n,0)+ 1'來代替。 '.get()'與'[]'類似,但它可以採用默認值。 – pepr 2013-03-12 12:47:25

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

有部分代碼可以刪除。 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

如果你打算去那些長度的話,應該考慮規範化輸入(即用戶.lower())。應該可能使用raw_input而不是輸入。您不會將自己放入Counter的空白區域剝離出來,不確定Counter是否自行處理。 – John 2013-03-12 13:27:36

+1

@johnthexiii:我的+1。他或她使用Python 3 - 然後'input()'確定。剝離添加。註釋中帶有'.split()'的選項。感謝您的意見;) – pepr 2013-03-12 13:37:27

+0

我不知道'輸入',謝謝。 – John 2013-03-12 13:46:17