![](/img/trans.png)
[英]Python: How can I count specific numbers of a list of lists without using .count?
[英]How to count specific numbers in massive on Python (not list)
我有一个程序可以生成从 -10 到 10 的随机数。我的任务是计算从 1 到 5 有多少元素在这个巨大的范围内。 问题是我不能使用 counter 或其他函数,因为TypeError: 'int' object is not iterable
。 我可以使用哪些功能来修复它?
import random
for i in range(51):
a = random.randint(-10, 10)
print(a)
您绝对可以为此使用collections.Counter
:
import random
import collections
c = collections.Counter(random.randint(-10, 11) for i in range(51))
print(c)
# Counter({-9: 7, 10: 7, -5: 5, 8: 3, 1: 3, -10: 3, -4: 3, -7: 3, 5: 3, 0: 3, -3: 2, 6: 2, 4: 2, 9: 2, 3: 1, -6: 1, 2: 1})
n = sum(c[i] for i in range(1,6)) # number of elements between 1 and 5
print(n)
# 10
你可以尝试这样的事情,如果随机int
在1
到5
范围内,则总和为1
,并且运行51
次。 最后,打印这个总和。
import random
print(sum(1 for i in range(51) if random.randint(-10, 11) in range(1, 5)))
上面的段相当于:
import random
a = 0
for i in range(51):
if random.randint(-10, 11) in range(1, 5):
a += 1
print(a)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.