所以我必须在列表中找到每个数字的出现,提示用户输入(1到100之间的数字),我的想法是计算每个数字,然后如果它发生则打印出来,并且如果没有发生,什么也不做。有什么想法可以解决这个问题吗?
il1 = eval(input("Enter integers between 1 and 100 "))
lst1 = []
for i in range(0,len(il1)):
lst1.append(il1[i])
for i in range(0,len(lst1)):
for j in range(1,100+1):
if lst1.count([j]) != 0:
print(i,"occurs",lst1.count[j],"times")
else:
continue
答案 0 :(得分:0)
在python中你做:
yourNum = 5
[1,2,3,4,5,5].count(yourNum)
> 2
答案 1 :(得分:0)
修改:由于eval
的使用被视为bad practice,我建议通过正则表达式解析数字。其他属性的Other选项也是可能的。
import re
LIMITS = (1, 100)
line = input("Enter integers between %d and %d: " % LIMITS)
# parse input for all possible numbers
numbers = [int(digits) for digits in re.findall(r'[0-9]+', line)]
# filter for valid numbers in given range
numbers = [n for n in numbers if LIMITS[0] <= n <= LIMITS[1]]
# count occurences; save in dict for easy use later
occurences = {}
for number in numbers:
if number in occurences:
occurences[number] += 1
else:
occurences[number] = 1
print(occurences)
是的,这可以挤成一行。但为了便于阅读,你不应该这样做。 : - )