如何从列表中随机选择特定序列?

时间:2018-09-25 13:33:47

标签: python

我有一个从(0是午夜)开始的小时数列表。

hour = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]

我想随机产生一个连续3个小时的序列。示例:

[3,6]

[15, 18]

[23,2]

,依此类推。 random.sample没有达到我想要的!

import random    
hourSequence = sorted(random.sample(range(1,24), 2))

有什么建议吗?

4 个答案:

答案 0 :(得分:1)

不确定您想要什么,但可能

import random

s = random.randint(0, 23)

r = [s, (s+3)%24]

r
Out[14]: [16, 19]

答案 1 :(得分:1)

注意:没有其他答案可以考虑可能的顺序[23,0,1]

请使用python lib中的itertools注意以下内容:

from itertools import islice, cycle
from random import choice

hours = list(range(24)) # List w/ 24h
hours_cycle = cycle(hours) # Transform the list in to a cycle
select_init = islice(hours_cycle, choice(hours), None) # Select a iterator on a random position

# Get the next 3 values for the iterator
select_range = []
for i in range(3):
    select_range.append(next(select_init))

print(select_range)

这将以循环方式在您的hours列表上打印三个值的序列,这些结果还将包括在您的结果中,例如[23,0,1]

答案 2 :(得分:0)

您可以尝试以下方法:

import random
hour = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
index = random.randint(0,len(hour)-2)
l = [hour[index],hour[index+3]]
print(l)

答案 3 :(得分:0)

您可以从已经创建的数组hour中获得一个随机数,然后取3位之后的元素:

import random

def random_sequence_endpoints(l, span):
    i = random.choice(range(len(l)))
    return [hour[i], hour[(i+span) % len(l)]]

hour = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
result = random_sequence_endpoints(hour, 3)

这不仅适用于上述小时列表示例,而且适用于包含其他元素的任何其他列表。

相关问题