简体   繁体   English

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

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

I run 1000 times of random.choice()from a list from 0-11.我从 0-11 的列表中运行 1000 次 random.choice()。 how to track of the number of random selections necessary before all 12 number have been selected at least once.如何跟踪至少选择一次所有 12 个数字之前所需的随机选择次数。 (Many will be selected more than once.) For instance, suppose the simulation yields the following sequence of random choices for a single trial: 2 5 6 8 2 9 11 10 6 3 1 9 7 10 0 7 0 7 4, where all 12 numbers have been selected at least once. (许多将被选择不止一次。)例如,假设模拟为单次试验产生以下随机选择序列:2 5 6 8 2 9 11 10 6 3 1 9 7 10 0 7 0 7 4,其中所有至少选择了一次 12 个号码。 The count for this example trial is 19. Collect the count for each trial of the simulation in a single list (ultimately consisting of 1,000 counts).此示例试验的计数为 19。将模拟的每个试验的计数收集在一个列表中(最终由 1,000 个计数组成)。

Here is a solution using collections.Counter as a container:这是一个使用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

Output:输出:

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

Distribution of the counts:计数分布:

计数直方图

One simple (but inefficient) way to do this would be with一种简单(但效率低下)的方法是使用

check = range(11)
if all(elem in randlist for elem in check): # check after each choice
    # do something

As others have said, tell us what you have tried so far so we can help further.正如其他人所说,请告诉我们您到目前为止所做的尝试,以便我们进一步提供帮助。

Maybe you can try using a set to store your results in a non-redundant way, while checking to see if all numbers have been used:也许您可以尝试使用 set 以非冗余方式存储您的结果,同时检查是否已使用所有数字:

import random

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM