【问题标题】:Selecting a random list element of length n in Python在 Python 中选择长度为 n 的随机列表元素
【发布时间】:2013-10-17 20:02:46
【问题描述】:

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

list1=[a,b,c,d,e,f,g,h]

我希望输出看起来像:

[c,d,e]

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

【问题讨论】:

  • 你想要3个连续元素还是3个随机元素?
  • 3 个连续元素

标签: python random


【解决方案1】:

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

random.sample(list1, 3)

演示:

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

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

def random_sublist(lst, length):
    start = random.randint(len(lst) - length)
    return lst[start:start + length]

它的工作原理是这样的:

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

【讨论】:

  • 我认为他想要一个连续的子列表,以他的例子为例。
  • 是的,我应该指定我想要一个连续的子列表
【解决方案2】:
idx = random.randint(0, len(list1)-3)
list1[idx:idx+3]

【讨论】:

  • 哇应该想到这一点。一个非常简单的解决方案!
【解决方案3】:

如果您希望结果环绕到列表的开头,您可以这样做:

idx = randint(0, len(list1))
(list1[idx:] + list1[:idx])[:3]

【讨论】:

    【解决方案4】:

    如果你想要的只是原始列表的一个随机子集,你可以使用

    import random
    random.sample(your_list, sample_size)
    

    但是,如果您希望子列表是连续的(就像您给出的示例一样),您最好选择两个随机索引并相应地对列表进行切片:

    a = random.randint(0, len(your_list) - sample_length)
    sublist = your_list[a:b+sample_length]
    

    【讨论】:

    • 这给出了随机长度的列表。
    • @MartijnPieters- 哎呀!误读了问题。已更正,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    • 2013-10-19
    • 2017-01-26
    相关资源
    最近更新 更多