[英]How to create a small random list from a larger list with Python
我想创建一个列表,其中包含从许多项目列表中随机选择的三个项目。 我就是这样做的,但我觉得使用 python 可能有一种更有效的(禅)方法。
import random
words = ['bacon', 'gorilla', 'phone', 'hamburger', 'mother']
small_list = []
while len(small_list) < 4:
word = random.choice(words)
if word not in small_list:
small_list.append(word)
预期的 output 将类似于:
small_list = ['phone', 'bacon', 'mother']
使用random.sample :
返回从种群序列或集合中选择的唯一元素的长度列表。 用于无放回的随机抽样。
import random
words = ['bacon', 'gorilla', 'phone', 'hamburger', 'mother']
small_list = random.sample(words, k=3)
print(small_list)
# ['mother', 'bacon', 'phone']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.