Python 计算数字的出现次数
因此,我必须在提示用户输入的列表中找到每个数字的出现次数(1到100之间的数字),我的想法是计算每个数字,如果出现,则打印出来,如果没有出现,则什么也不做。有什么好主意吗Python 计算数字的出现次数,python,Python,因此,我必须在提示用户输入的列表中找到每个数字的出现次数(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
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
在python中,您可以执行以下操作:
yourNum = 5
[1,2,3,4,5,5].count(yourNum)
> 2
Edit:由于
eval
的用法被认为是,我建议通过正则表达式解析数字。也可以使用具有其他属性的选项
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)
重新导入
极限=(1100)
行=输入(“输入介于%d和%d之间的整数:”%LIMITS)
#分析所有可能数字的输入
numbers=[int(数字)表示re.findall中的数字(r'[0-9]+',行)]
#筛选给定范围内的有效数字
数字=[n表示数字中的n如果限制[0]为什么要使用eval
?为什么要调用count()`如果将j
封装在一个列表中?为什么您要尝试使用索引j
访问count
?也许可以查看一下您编写的类似java的python代码,您可以在python中这样做,只需一行代码,就可以重复您为什么要对给定的输入使用regex?@user1767754在OP的示例代码中,整数列表是使用eval
。这对我来说很危险,而正则表达式似乎是一种替代的、健壮的解决方案。这太过分了。@user1767754:s[int(s)代表s in.''。加入(c if c.isdigit()else''代表c in line.split()]
然后?:-)@SilverCrafter7:很高兴它有帮助。:-)