是否有一种Pythonic方法可以从列表或numpy数组中采样N个连续元素
是否有一种 Pythonic 方法可以从列表或 numpy 数组中选择 N 个连续元素。
所以假设:
Choice = [1,2,3,4,5,6]
我想通过在选择中随机选择元素 X 以及选择后的 N-1 个连续元素来创建一个长度为 N 的新列表。
因此,如果:
X = 4
N = 4
结果列表将是:
Selection = [5,6,1,2]
我认为类似于以下内容的内容会起作用。
S = []
for i in range(X,X+N):
S.append(Selection[i%6])
但我想知道是否有一个 python 或 numpy 函数可以一次选择更有效的元素。
回答
使用itertools,特别是islice和cycle。
start = random.randint(0, len(Choice) - 1)
list(islice(cycle(Choice), start, start + n))
cycle(Choice)是一个无限序列,重复您的原始列表,以便切片start:start + n在必要时换行。
- @phntm: For large inputs, it's almost guaranteed to be slower than any other solution, as it's `O(n)` on both memory usage and processing time (`islice` can't skip values, `cycle` stores them all until the input is exhausted). For small inputs, it hardly matters what solution you use.
THE END
二维码