2017-08-05 26 views
1

我試圖計算列表中數字的出現次數。所以基本上,我有一個列表:在用戶輸入時計算列表中出現的數字的數量

lst = [23,23,25,26,23] 

和程序將首先提示用戶從列表中選擇一個數字。

"Enter target number: " 

例如,如果目標是23,那麼它將打印出列表中出現多少次23。

output = 3 #since there are three 23s in the list 

這裏就是我試過,它導致了一個無限循環:

lst = [23,23,24,25,23] 
count = 0 
i = 0 

prompt= int(input("Enter target: ")) 
while i< len(lst)-1: 
    if prompt == lst[i]: 
     count+=1 
     print(count) 
    else: 
     print("The target does not exist in the list") 

我不應該使用任何圖書館,所以我真的很感激,如果有人可以幫助我通過指向在我寫的代碼中找出錯誤。此外,我更喜歡'while循環'的用法,因爲我在練習使用while循環,而我至少明白這一點。

+4

你需要一個'我+ = 1'地方。你的代碼中''i''總是'0'。 – smarx

回答

1

你應該循環後打印了,不是每個單迴路

lst = [23,23,24,25,23] 
count = 0 
i = 0 

prompt= int(input("Enter target: ")) 
while i< len(lst): 
    if prompt == lst[i]: 
     count+=1 
    i+=1 

if count>0: 
    print(count) 
else: 
    print("The target does not exist in the list") 
+0

該代碼接近正確,但循環條件應爲'i smarx

+0

Wonjiin Kim很好的回答這個問題的嘗試!但是,while循環中的條件會**跳過列表的最後一個元素。 :/看到我的答案是正確的條件! – gsamaras

+0

是的,你們是對的!我複製了這個問題的代碼,並沒有注意到這一點。我現在編輯,謝謝! – Wonjin

2

i是0 總是,這導致無限循環。考慮在循環結束時將i增加1。

而且你需要去,直到列表的末尾,所以while循環的條件應該是:

while i < len(lst): 

將所有內容放在一起應該給這個:

while i< len(lst)a: 
    if prompt == lst[i]: 
     count+=1 
     print(count) 
    else: 
     print("The target does not exist in the list") 
    i += 1 

其輸出:

Enter target: 23 
1 
2 
The target does not exist in the list 
The target does not exist in the list 
3 

這裏的方式是更Python實現會是什麼樣子:

lst = [23,23,24,25,23] 
count = 0 

target = int(input("Enter target: ")) 
for number in lst: 
    if number == target: 
    count += 1 

print(count) 

輸出:

Enter target: 23 
3 

或者,如果你想使用一個內置的功能,你可以嘗試:

print(lst.count(target)) 

as smarx指出。

+0

甚至更​​多的Pythonic可能是'print(lst.count(target))'? – smarx

+0

@smarx絕對!我編輯了我的答案。但是,我確實離開了我的初始方法,因爲它有點補習恕我直言。 – gsamaras

1

您可以使用count此任務:

lst = [23,23,24,25,23] 

prompt= int(input("Enter target: ")) 
cnt = lst.count(prompt) 
# print(cnt) 
if cnt: 
    print(cnt) 
else: 
    print("The target does not exist in the list") 

輸出:

Enter target: 23 
3 

Enter target: 3 
The target does not exist in the list 
1

您可以使用collections.Counter,旨在執行您的願望。例如:

>>> from collections import Counter 

>>> lst = [23,23,25,26,23] 
>>> my_counter = Counter(lst) 
#    v element for which you want to know the count 
>>> my_counter[23] 
3 

official document提到:

Counter是用於計數可哈希對象的字典子類。它是一個無序集合,其中元素作爲字典鍵存儲,並且它們的計數作爲字典值存儲在 中。計數允許爲任何整數值,包括零或負計數。櫃檯類 類似於其他語言的箱包或多配套。

1

您可以嘗試使用filter

>>> lst = [23,23,24,25,23] 
>>> prompt= int(input("Enter target: ")) 
Enter target: 23 
>>> len(filter(lambda x: x==prompt, lst)) 
3 

>>> prompt= int(input("Enter target: ")) 
Enter target: 24 
>>> len(filter(lambda x: x==prompt, lst)) 
1 
相關問題