【发布时间】:2021-12-30 09:06:54
【问题描述】:
目标:打印随机选择的列表元素,至少从 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
如果还有什么我可以添加到帖子中的,请告诉我。
【问题讨论】:
-
你为什么使用
eval()? -
你不需要在
BENEFITS周围加上[]。已经是清单了。您正在创建一个只有一个元素的新列表。 -
觉得有帮助,打算删掉
-
random.randint(3, len(BENEFITS)-1))毫无意义。len(BENEFITS)-1是 3。所以你要求一个从 3 到 3 的随机整数,它总是 3! -
k和v是什么?没有包含键和值的字典。
标签: python list random valueerror