有没有一种从列表或numpy数组中选择N个连续元素的方法?
那么假设:
Choice = [1,2,3,4,5,6]
我想创建一个长度为N的新列表,方法是在choice中随机选择元素X以及选择后的N-1个连续元素。
因此,如果:
X = 4
N = 4
结果列表将是:
Selection = [5,6,1,2]
我认为类似于下面的方法将会起作用。
S = []
for i in range(X,X+N):
S.append(Selection[i%6])
但我想知道是否有一个python或numpy函数可以一次选择更有效的元素。
发布于 2021-01-27 11:27:16
既然你问的是最有效的方法,我创建了一个小基准来测试这个线程中提出的解决方案。
我将您当前的解决方案重写为:
def op(choice, x):
n = len(choice)
selection = []
for i in range(x, x + n):
selection.append(choice[i % n])
return selection
其中choice
是输入列表,x
是随机索引。
如果choice
包含1_000_000随机数,则结果如下:
chepner: 0.10840400000000017 s
nick: 0.2066781999999998 s
op: 0.25887470000000024 s
fountainhead: 0.3679908000000003 s
完整代码
import random
from itertools import cycle, islice
from time import perf_counter as pc
import numpy as np
def op(choice, x):
n = len(choice)
selection = []
for i in range(x, x + n):
selection.append(choice[i % n])
return selection
def nick(choice, x):
n = len(choice)
return [choice[i % n] for i in range(x, x + n)]
def fountainhead(choice, x):
n = len(choice)
return np.take(choice, range(x, x + n), mode='wrap')
def chepner(choice, x):
n = len(choice)
return list(islice(cycle(choice), x, x + n))
results = []
n = 1_000_000
choice = random.sample(range(n), n)
x = random.randint(0, n - 1)
# Correctness
assert op(choice, x) == nick(choice,x) == chepner(choice,x) == list(fountainhead(choice,x))
# Benchmark
for f in op, nick, chepner, fountainhead:
t0 = pc()
f(choice, x)
t1 = pc()
results.append((t1 - t0, f))
for t, f in sorted(results):
print(f'{f.__name__}: {t} s')
https://stackoverflow.com/questions/65912024
复制相似问题