新的蟒蛇,所以所有的帮助是感谢!我确实检查并找到了几个计数帖子,但找不到从列表中打印出最上面的事件的任何信息。(即3次发生6次,4次发生4次,2次发生3次)
目标:,我想让代码随机打印1000个数字,然后能够选择显示多少。
例如,num = 0,5,12,5,22,12,0,32,22,0,5,我希望能够看到前3个重复数,以及这个数字发生了多少次。0-4次,5-3次,12-2次。
代码进展#有效的尝试是
随机打印1000次
import random
for x in range(1001):
print(random.randint(0,1001))
将随机画直接附加到数字上
import random
num = []
for x in range(1001):
num.append(random.randint(0,1001))
print(num)
包括提示符,以获取要查看的整数数。
import random
num = []
for x in range(1001):
num.append(random.randint(0,1001))
highscore = input("Please enter howmany numbers you'd like to see: ")
print("The top", highscore, "repeated numbers are: ", num)
问题左:如何打印高分的数字(本部分0-4次,5-3次,12-2次)。
尝试计数问题(每次打印0。在打印中添加num以确认"y“是否在列表中)
import random
#creates list
num = []
for x in range(0,10):
num.append(random.randint(0,10))
highscore = input("input number of reoccurrence's you want to see: ")
y = num.count(highscore)
print(num, y)
发布于 2022-04-12 14:45:36
您可以从most_common
库中的Counter
类中使用collections
方法。文档
from collections import Counter
import random
number_of_elements = 1000
counter = Counter([random.randint(0,1001) for i in range(number_of_elements)])
# printing 3 most common elements.
print(counter.most_common(3))
产出:
[(131, 6), (600, 5), (354, 5)]
这个输出意味着数字131是最常见的,重复6次,然后600是第二次最常见的,它是重复5次等等。
发布于 2022-04-12 14:50:12
这是由于无效的类型。试一试
y = num.count(int(highscore))
那就很好了,
input number of reoccurrence's you want to see: 4 [5, 4, 0, 6, 0, 2, 7, 9, 3, 1] 1
https://stackoverflow.com/questions/71844548
复制相似问题