随机选择列表元素

Random selection of list elements

目标:打印列表元素的随机选择,至少 1 到所有,作为列表理解。

尝试:

import random

BENEFITS = ['foo', 'bar', 'idk', 'lol']

selection = [sorted(random.sample(BENEFITS, random.randint(1, len(BENEFITS))]
print(selection)

期望的输出:

foo, idk

值错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-17-407cc8d7fbfe> in <module>
----> 1 v = [[k, eval(v)] for k, v in sorted(random.sample([BENEFITS], random.randint(3, len(BENEFITS)-1)))]
      2 
      3 print(v)

~\Anaconda3\lib\random.py in sample(self, population, k)
    361         n = len(population)
    362         if not 0 <= k <= n:
--> 363             raise ValueError("Sample larger than population or is negative")
    364         result = [None] * k
    365         setsize = 21        # size of a small set minus size of an empty list

ValueError: Sample larger than population or is negative

如果我还有什么要补充的,请告诉我post。

在尝试将其放入字典或作为列表理解时,我遇到了很多不同的错误。

最少的代码答案:

import random

BENEFITS = ['foo', 'bar', 'idk', 'lol']

selection = sorted(random.sample(BENEFITS, random.randint(1, len(BENEFITS))))
print(selection)

您可以使用模块 random 中的 choices。那么

from random import choices
BENEFITS = ['foo', 'bar', 'idk', 'lol']
print(choices(BENEFITS,k=2))

这样,函数 choices returns 来自 BENEFITS.

长度 k=2 的随机样本