在Python中选择长度为n的随机列表元素

use*_*074 3 python random

我知道你可以使用random.choice从列表中选择一个随机元素,但我试图选择长度为3的随机元素.例如,

list1=[a,b,c,d,e,f,g,h]
Run Code Online (Sandbox Code Playgroud)

我希望输出看起来像:

[c,d,e]
Run Code Online (Sandbox Code Playgroud)

基本上我想从列表中生成随机子列表.

Mar*_*ers 19

你想要一个样本 ; 用于random.sample()选择3个元素的列表:

random.sample(list1, 3)
Run Code Online (Sandbox Code Playgroud)

演示:

>>> import random
>>> list1 = ['a', 'b', 'c' ,'d' ,'e' ,'f', 'g', 'h']
>>> random.sample(list1, 3)
['e', 'b', 'a']
Run Code Online (Sandbox Code Playgroud)

如果您需要一个子列表,那么您将无法选择0和长度减去3之间的随机起始索引:

def random_sublist(lst, length):
    start = random.randint(len(lst) - length)
    return lst[start:start + length]
Run Code Online (Sandbox Code Playgroud)

其工作方式如下:

>>> def random_sublist(lst, length):
...     start = random.randint(len(lst) - length)
...     return lst[start:start + length]
... 
>>> random_sublist(list1, 3)
['d', 'e', 'f']
Run Code Online (Sandbox Code Playgroud)


Ste*_*sop 6

idx = random.randint(0, len(list1)-3)
list1[idx:idx+3]
Run Code Online (Sandbox Code Playgroud)