2017-08-05 51 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 
相关问题