我正在尝试制作一个程序,它将输出从用户输入的一系列数字(没有特定范围)中显示数字7的次数。每个数字将是一个单独的输入,而不是作为一个输入。
我搜索了很多地方,但我找到的解决方案涉及到预先制作的列表中的字母、单词或数字,而不是用户输入的int,并且在我试图进行修改时出错。我肯定我错过了一些很明显的东西,但我不知道该怎么做。
(我尝试了计数器,如果是== 100,计数(100),用于范围内的I,等等--但我显然走错了路)
我的出发点是修改这个打印最高数字的文件,因为我的目标是使用类似的格式:
x = 0
done = False
while not done:
print("Enter a number (0 to end): ")
y = input()
num = int(y)
if num != 0:
if num > x:
x = num
else:
done = True
print(str(x))谢谢你对此的任何建议。
发布于 2017-06-07 09:17:30
尝试以下几点:
x = ''
done = False
while not done:
print("Enter a number (0 to end): ")
y = input()
if y != '0':
x = x + y
else:
done = True
print(x.count('7'))发布于 2017-06-07 09:10:03
考虑一下
from collections import Counter
nums = []
c = Counter()
done = False
while not done:
y = int(input("Enter a number (0 to end): "))
if y == 0:
done = True
else:
c.update([y])
print(c)示例输出:
Enter a number (0 to end): 1
Counter({1: 1})
Enter a number (0 to end): 2
Counter({1: 1, 2: 1})
Enter a number (0 to end): 2
Counter({2: 2, 1: 1})
Enter a number (0 to end): 2
Counter({2: 3, 1: 1})
Enter a number (0 to end): 0如果用户输入一个非整数,这显然会中断.如果需要,移除int(input..)或添加try-except。
发布于 2017-06-07 09:08:35
您可以使用下面的代码示例。它期望第一个输入作为要在列表中搜索的数字。后面跟着单行上的数字列表。
x = 0
done = False
count = 0
i = input("Which number to search: ")
print("Enter list of numbers to search number",i,", enter each on separate line and 0 to end): ")
while not done:
j = input()
num = int(j)
if int(j) == 0 :
print("exitting")
break
else:
if j == i:
count += 1
print("Found number",i,"for",count,"number of times")https://stackoverflow.com/questions/44407787
复制相似问题