我知道你可以使用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)
| 归档时间: |
|
| 查看次数: |
4198 次 |
| 最近记录: |