Python-3.x 从用户输入中计算特定数字的频率
Python-3.x Count the frequency of a specific number from user input
我正在尝试编写一个程序来输出 用户输入的一系列数字(没有特定范围)中数字 7 出现的次数。 每个数字都是一个单独的输入,而不是一个。
我进行了广泛的搜索,但我发现的解决方案涉及来自预制列表的字母、单词或数字,而不是来自用户输入的 int,并且在我尝试有目的地修改时出错。我确定我遗漏了一些非常明显的东西,但我不知道该怎么做。
(我尝试了 Counter,if num == 100,count(100),for i in range,等等 - 但我显然走错了路)
我的出发点是尝试修改打印最高数字的这个,因为我的目标是类似的格式:
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))
感谢您对此的任何建议。
您可以使用下面的代码示例。它期望第一个输入是您要在列表中搜索的数字。后跟号码列表,每个号码单独一行。
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")
考虑
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
。
尝试以下操作:
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'))
我正在尝试编写一个程序来输出 用户输入的一系列数字(没有特定范围)中数字 7 出现的次数。 每个数字都是一个单独的输入,而不是一个。
我进行了广泛的搜索,但我发现的解决方案涉及来自预制列表的字母、单词或数字,而不是来自用户输入的 int,并且在我尝试有目的地修改时出错。我确定我遗漏了一些非常明显的东西,但我不知道该怎么做。
(我尝试了 Counter,if num == 100,count(100),for i in range,等等 - 但我显然走错了路)
我的出发点是尝试修改打印最高数字的这个,因为我的目标是类似的格式:
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))
感谢您对此的任何建议。
您可以使用下面的代码示例。它期望第一个输入是您要在列表中搜索的数字。后跟号码列表,每个号码单独一行。
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")
考虑
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
。
尝试以下操作:
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'))