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

2024-10-03 00:22:34 发布

您现在位置: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]

等等。随机抽样没有达到我想要的!你知道吗

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

有什么建议吗?你知道吗


Tags: sampleimport示例列表range序列random建议
3条回答

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

import random

s = random.randint(0, 23)

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

r
Out[14]: [16, 19]

注意:其他答案都没有考虑可能的序列[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]。你知道吗

你可以试试这个:

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)

相关问题 更多 >