繁体   English   中英

如何使用 Python 从较大的列表中创建一个小的随机列表

[英]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']

这个答案中,您可以使用random.sample()来选择一组数据。

small_list = random.sample(words, 4)

演示

暂无
暂无

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

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