Skip to main content
 首页 » 编程设计

python之根据用户输入计算列表中数字的出现次数

2025年05月04日18jpfss

我正在尝试计算列表中某个数字出现的次数。所以基本上,我有一个列表:

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 循环。

请您参考如下方法:

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 

顺便说一下,这里是一个更像 pythonic 的实现:

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

正如 smarx 指出的那样。