在 Python 中选择长度为 n 的随机列表元素
问题描述:
我知道您可以使用 random.choice 从列表中选择一个随机元素,但我正在尝试选择长度为 3 的随机元素.例如,
I know you can use random.choice to choose a random element from a list, but I am trying to choose random elements of length 3. For example,
list1=[a,b,c,d,e,f,g,h]
我希望输出看起来像:
[c,d,e]
本质上我想从列表中生成随机子列表.
Essentially I want to generate random sub-lists from the list.
答
idx = random.randint(0, len(list1)-3)
list1[idx:idx+3]