簡體   English   中英

如何在 Python 上大量計算特定數字(未列出)

[英]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

你可以嘗試這樣的事情,如果隨機int15范圍內,則總和為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM