[英](Python)How do I make a function to count the amount of specific numbers in a randomized list?
我的程序是為 1000 的范圍創建一個 1-10 的隨機列表,每個數字必須通過 1-10 隨機化,然后一旦完成。 我需要確定 1000 個隨機數字中有多少個 1、2、3 和 4,等等。
import random
#Printing a random list of 1 through 10
#loop to loop 1000 times
for i in range(1000):
#lisitng random numbers 1 through 10 inclusive
l1 = random.randint(1, 10)
l2 = random.randint(1, 10)
l3 = random.randint(1, 10)
l4 = random.randint(1, 10)
l5 = random.randint(1, 10)
l6 = random.randint(1, 10)
l7 = random.randint(1, 10)
l8 = random.randint(1, 10)
l9 = random.randint(1, 10)
l10 = random.randint(1, 10)
#printing the numbers in a list form
print(l1,l2,l3,l4,l5,l6,l7,l8,l9,l10)
#A function to identify how many X are there in each number
如果您需要這方面的更多信息,請在評論中告訴我。
首先你需要生成列表,最簡單的方法是這樣的:
randomList = [random.randint(1, 10) for x in range(1, 1000)]
接下來,您需要計算該數組中每個數字的數量,您可以這樣做:
randomCounts = [ (x, randomList.count(x)) for x in range(1, 10)]
這將 output 元組數組,其中元組的第一個值表示一個數字,第二個表示該數字在 randomList 中出現的頻率。
然后,您可以執行以下操作來查找數字 N 在該列表中出現的頻率:
amount = randomCounts[n - 1][1]
這應該可以解決問題:
import random
random_list = []
for i in range(1000):
random_list.append(random.randint(1, 10))
for i in range(10):
print("{} was in the list exactly {} times.".format(i+1, random_list.count(i+1)))
使用collections.Counter
計算每個數字的出現次數,並使用random.choices
在一個范圍內創建隨機數:
from collections import Counter
from random import choices
counter = Counter(choices(range(1, 10 + 1), k=1000))
for key, value in sorted(counter.items()):
print(f"Number of {key}s: {value}")
Output:
Number of 1s: 87
Number of 2s: 102
Number of 3s: 93
Number of 4s: 116
Number of 5s: 109
Number of 6s: 79
Number of 7s: 105
Number of 8s: 105
Number of 9s: 104
Number of 10s: 100
>>>
您似乎想要:
因此,讓我們創建一個包含 1000 個項目的列表,其中每個項目可以是 1 到 10 范圍內的隨機 integer:
import random
my_list = [random.randint(1, 10) for x in range(0, 1000)]
然后,讓我們數一下my_list
中有多少個 1、2、3、...、10:
count = [my_list.count(i+1) for i in range(0, 10)]
現在count
是一個類似的列表:
1s 的數量 | 2s數 | ... | 10s 數量 |
---|---|---|---|
32 | 21 | ... | 43 |
如果要打印(python 3.x):
for idx, number in enumerate(count):
print(f'There are {number} item of {idx+1}s')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.