如何计算随机列表中出现的数字列表 Python

how to count a list of numbers which occour in a random list Python

I 运行 1000 次 random.choice() 来自 0-11 的列表。如何跟踪至少选择一次所有 12 个数字之前所需的随机选择次数。 (许多将不止一次被选中。) 例如,假设模拟产生以下随机选择序列 试验:2 5 6 8 2 9 11 10 6 3 1 9 7 10 0 7 0 7 4,其中所有 12 个数字至少被选择一次。此示例试验的计数为 19。收集每次试验的计数 在单个列表中进行模拟(最终由 1,000 个计数组成)。

也许您可以尝试使用一组以非冗余方式存储您的结果,同时检查是否所有数字都已被使用:

import random

guesses = set()
count = 0
for i in range(1000):
    count += 1
    guesses.add(random.randrange(0, 12))
    if len(guesses) == 12:
        break
print(count)

这将为您计数 1 次。 mozway 在他们的回答中概述了一个更好的方法。

您可以 运行 代码一百万次并将结果收集在一个列表中,然后像这样绘制它(使用 while 条件更新):

import random
import numpy as np
from matplotlib import pyplot as plt

counts = []
for i in range(100000):
    guesses = set()
    count = 0
    while len(guesses) != 12:
        count += 1
        guesses.add(random.randrange(0, 12))

    counts.append(count)

fig = plt.figure(figsize=(8, 6))
x = np.array([i for i in range(np.max(np.array(counts)))])
y = np.array([counts.count(i) for i in range(np.max(np.array(counts)))])
plt.bar(x, y)
plt.xlabel('Number of Guesses')
plt.ylabel('Frequency')
plt.show()

因此 [counts.count(i) for i in range(np.max(np.array(counts)))] 将为您提供一个列表,列出猜谜游戏在列表的给定位置完成的频率。 IE。列表的第一个值是 0,因为游戏不可能只用 1 次猜测就结束,但是在位置 25(25 次猜测)有超过 2000 次这种情况发生

这里有一个使用 collections.Counter 作为容器的解决方案:

from collections import Counter
import random

nums = list(range(12))
n = 1000
counts = [0]*n
for trial in range(n):
    c = Counter()
    while len(c)<len(nums):
        c[random.choice(nums)]+=1
    counts[trial] = sum(c.values()) # c.total() in python ≥ 3.10

counts

输出:

[28, 24, 39, 27, 40, 36, ...] # 1000 elements

计数分布: