在 python 时间跳过列表的特定范围
skipping a certain range of a list at time in python
我有一个数组,我想选择前 2 个或范围,跳过下 2 个,选择下 2 个并继续此操作直到列表结束
list = [2, 4, 6, 7, 9,10, 13, 11, 12,2]
results_wanted = [2,4,9,10,12,2] # note how it skipping 2. 2 is used here as and example
有没有办法在 python 中实现这个?
您可以尝试使用 range(start, end, skip)
进行迭代
并且您可以指定在序列中添加多少个 (add=2
) 和跳过多少个 (skip=2
)
list1 = [2, 4, 6, 7, 9,10, 13, 11, 12,2, 4, 6, 7, 9,10, 13, 11, 12,2]
list2 = []
add = 2
skip = 2
for i in range(0, len(list1), skip+add):
list2 += list1[i:i+add]
print(list2)
输出:
[2, 4, 9, 10, 12, 2, 7, 9, 11, 12]
顺便说一句,你应该避免使用 Python 保留字 list
作为变量名。
我没有使用任何 python 预构建技术。我在 if-else 条件下使用传统的 for 循环
- 我们必须根据特定数字跳过。
- 这个skip需要根据我定义为skipMode的boolean参数来完成
- 如果 skipMode 为真,则不会将数字添加到列表中
4 这个skipMode会根据skipNumber
改变
test = [2, 4, 6, 7, 9,10, 13, 11, 12,2]
def skipElementsByPositions(test,skip):
if(skip> len(test)):
return -1
else:
desireList = []
skipMode = False
for i in range(0,len(test)):
if skipMode==False:
desireList.append(test[i])
if (i+1)%skip==0:
skipMode=not skipMode
return desireList
print(skipElementsByPositions(test,2)) #2,4,9,10,12,2
print(skipElementsByPositions(test,3)) #2, 4, 6, 13, 11, 12
from itertools import compress, cycle
results = list(compress(lst, cycle([1,1,0,0])))
或
results = [x for i, x in enumerate(lst) if i % 4 < 2]
或者如果您不再需要原始列表,那么可以修改它而不是构建一个新列表(如果您确实想要一个新列表,您仍然可以在副本上使用它):
del lst[2::4], lst[2::3]
具有一百万个元素的列表的基准:
8.6 ms ± 0.1 ms _del_slices
11.6 ms ± 0.1 ms _compress_bools
13.6 ms ± 0.0 ms _compress_ints
14.1 ms ± 0.0 ms _copy_del_slices
22.6 ms ± 0.2 ms _copy_slices
46.0 ms ± 0.2 ms Black_Raven
59.5 ms ± 0.4 ms Vikrant_Sharma
84.8 ms ± 0.1 ms _enumerate_modulo
161.8 ms ± 0.6 ms RCvaram
不包括 numpy 解决方案,因为我必须为此切换到较旧的 Python 版本,并且因为比较没有意义(np.array(lst)
已经花费了约 55 毫秒)。
基准代码(Try it online!):
def _compress_ints(lst):
return list(compress(lst, cycle([1,1,0,0])))
def _compress_bools(lst):
return list(compress(
lst,
cycle(chain(repeat(True, 2),
repeat(False, 2)))
))
def _enumerate_modulo(lst):
return [x for i, x in enumerate(lst) if i % 4 < 2]
def _del_slices(lst):
del lst[2::4], lst[2::3]
return lst
def _copy_del_slices(lst):
results = lst[:]
del results[2::4], results[2::3]
return results
def _copy_slices(lst):
a = lst[::4]
b = lst[1::4]
results = [None] * (len(a) + len(b))
results[::2] = a
results[1::2] = b
return results
def Black_Raven(list1):
add = skip = 2
list2 = []
for i in range(0, len(list1), skip+add):
list2 += list1[i:i+add]
return list2
def Vikrant_Sharma(l):
n = 2
return [x for i in range(0, len(l), n + n) for x in l[i: i + n]]
def RCvaram(test):
skip = 2
desireList = []
skipMode = False
for i in range(0,len(test)):
if skipMode==False:
desireList.append(test[i])
if (i+1)%skip==0:
skipMode=not skipMode
return desireList
funcs = [_compress_ints, _compress_bools, _enumerate_modulo, _del_slices, _copy_del_slices, _copy_slices, Black_Raven, Vikrant_Sharma, RCvaram]
from timeit import default_timer as timer
from itertools import compress, cycle, repeat, chain, islice
from random import shuffle
from statistics import mean, stdev
import gc
# Correctness
lst = [2, 4, 6, 7, 9,10, 13, 11, 12,2]
results_wanted = [2,4,9,10,12,2]
for func in funcs:
assert func(lst[:]) == results_wanted
for n in range(100):
lst = list(range(n))
expect = funcs[0](lst[:])
for func in funcs:
assert func(lst[:]) == expect, func.__name__
# Speed
times = {func: [] for func in funcs}
def stats(func):
ts = [t * 1e3 for t in sorted(times[func])[:3]]
return f'{mean(ts):5.1f} ms ± {stdev(ts):.1f} ms'
original = list(range(1000000))
for _ in range(15):
shuffle(funcs)
for func in funcs:
lst = original.copy()
gc.collect()
t0 = timer()
result = func(lst)
t = timer() - t0
del result
times[func].append(t)
for func in sorted(funcs, key=stats):
print(stats(func), func.__name__)
取 n
个元素并跳过下一个 n
。
l = [2, 4, 6, 7, 9, 10, 13, 11, 12, 2]
n = 2
wanted = [x for i in range(0, len(l), n + n) for x in l[i: i + n]]
### Output : [2, 4, 9, 10, 12, 2]
因为你有一个 numpy 标签,这里是 numpy 方法。
使用面具:
lst = [2, 4, 6, 7, 9,10, 13, 11, 12,2]
a = np.array(lst)
mask = [True, True, False, False]
n = (len(a)+3)//4
a[np.tile(mask, n)[:len(a)]]
或中间重塑为二维数组:
n = (len(a)+3)//4
extra = n*4-len(a)
(np
.pad(a, (0, extra), mode='constant', constant_values=0)
.reshape(-1,4)
[:,:2]
.ravel()
)
输出:array([ 2, 4, 9, 10, 12, 2])
我有一个数组,我想选择前 2 个或范围,跳过下 2 个,选择下 2 个并继续此操作直到列表结束
list = [2, 4, 6, 7, 9,10, 13, 11, 12,2]
results_wanted = [2,4,9,10,12,2] # note how it skipping 2. 2 is used here as and example
有没有办法在 python 中实现这个?
您可以尝试使用 range(start, end, skip)
并且您可以指定在序列中添加多少个 (add=2
) 和跳过多少个 (skip=2
)
list1 = [2, 4, 6, 7, 9,10, 13, 11, 12,2, 4, 6, 7, 9,10, 13, 11, 12,2]
list2 = []
add = 2
skip = 2
for i in range(0, len(list1), skip+add):
list2 += list1[i:i+add]
print(list2)
输出:
[2, 4, 9, 10, 12, 2, 7, 9, 11, 12]
顺便说一句,你应该避免使用 Python 保留字 list
作为变量名。
我没有使用任何 python 预构建技术。我在 if-else 条件下使用传统的 for 循环
- 我们必须根据特定数字跳过。
- 这个skip需要根据我定义为skipMode的boolean参数来完成
- 如果 skipMode 为真,则不会将数字添加到列表中 4 这个skipMode会根据skipNumber 改变
test = [2, 4, 6, 7, 9,10, 13, 11, 12,2]
def skipElementsByPositions(test,skip):
if(skip> len(test)):
return -1
else:
desireList = []
skipMode = False
for i in range(0,len(test)):
if skipMode==False:
desireList.append(test[i])
if (i+1)%skip==0:
skipMode=not skipMode
return desireList
print(skipElementsByPositions(test,2)) #2,4,9,10,12,2
print(skipElementsByPositions(test,3)) #2, 4, 6, 13, 11, 12
from itertools import compress, cycle
results = list(compress(lst, cycle([1,1,0,0])))
或
results = [x for i, x in enumerate(lst) if i % 4 < 2]
或者如果您不再需要原始列表,那么可以修改它而不是构建一个新列表(如果您确实想要一个新列表,您仍然可以在副本上使用它):
del lst[2::4], lst[2::3]
具有一百万个元素的列表的基准:
8.6 ms ± 0.1 ms _del_slices
11.6 ms ± 0.1 ms _compress_bools
13.6 ms ± 0.0 ms _compress_ints
14.1 ms ± 0.0 ms _copy_del_slices
22.6 ms ± 0.2 ms _copy_slices
46.0 ms ± 0.2 ms Black_Raven
59.5 ms ± 0.4 ms Vikrant_Sharma
84.8 ms ± 0.1 ms _enumerate_modulo
161.8 ms ± 0.6 ms RCvaram
不包括 numpy 解决方案,因为我必须为此切换到较旧的 Python 版本,并且因为比较没有意义(np.array(lst)
已经花费了约 55 毫秒)。
基准代码(Try it online!):
def _compress_ints(lst):
return list(compress(lst, cycle([1,1,0,0])))
def _compress_bools(lst):
return list(compress(
lst,
cycle(chain(repeat(True, 2),
repeat(False, 2)))
))
def _enumerate_modulo(lst):
return [x for i, x in enumerate(lst) if i % 4 < 2]
def _del_slices(lst):
del lst[2::4], lst[2::3]
return lst
def _copy_del_slices(lst):
results = lst[:]
del results[2::4], results[2::3]
return results
def _copy_slices(lst):
a = lst[::4]
b = lst[1::4]
results = [None] * (len(a) + len(b))
results[::2] = a
results[1::2] = b
return results
def Black_Raven(list1):
add = skip = 2
list2 = []
for i in range(0, len(list1), skip+add):
list2 += list1[i:i+add]
return list2
def Vikrant_Sharma(l):
n = 2
return [x for i in range(0, len(l), n + n) for x in l[i: i + n]]
def RCvaram(test):
skip = 2
desireList = []
skipMode = False
for i in range(0,len(test)):
if skipMode==False:
desireList.append(test[i])
if (i+1)%skip==0:
skipMode=not skipMode
return desireList
funcs = [_compress_ints, _compress_bools, _enumerate_modulo, _del_slices, _copy_del_slices, _copy_slices, Black_Raven, Vikrant_Sharma, RCvaram]
from timeit import default_timer as timer
from itertools import compress, cycle, repeat, chain, islice
from random import shuffle
from statistics import mean, stdev
import gc
# Correctness
lst = [2, 4, 6, 7, 9,10, 13, 11, 12,2]
results_wanted = [2,4,9,10,12,2]
for func in funcs:
assert func(lst[:]) == results_wanted
for n in range(100):
lst = list(range(n))
expect = funcs[0](lst[:])
for func in funcs:
assert func(lst[:]) == expect, func.__name__
# Speed
times = {func: [] for func in funcs}
def stats(func):
ts = [t * 1e3 for t in sorted(times[func])[:3]]
return f'{mean(ts):5.1f} ms ± {stdev(ts):.1f} ms'
original = list(range(1000000))
for _ in range(15):
shuffle(funcs)
for func in funcs:
lst = original.copy()
gc.collect()
t0 = timer()
result = func(lst)
t = timer() - t0
del result
times[func].append(t)
for func in sorted(funcs, key=stats):
print(stats(func), func.__name__)
取 n
个元素并跳过下一个 n
。
l = [2, 4, 6, 7, 9, 10, 13, 11, 12, 2]
n = 2
wanted = [x for i in range(0, len(l), n + n) for x in l[i: i + n]]
### Output : [2, 4, 9, 10, 12, 2]
因为你有一个 numpy 标签,这里是 numpy 方法。
使用面具:
lst = [2, 4, 6, 7, 9,10, 13, 11, 12,2]
a = np.array(lst)
mask = [True, True, False, False]
n = (len(a)+3)//4
a[np.tile(mask, n)[:len(a)]]
或中间重塑为二维数组:
n = (len(a)+3)//4
extra = n*4-len(a)
(np
.pad(a, (0, extra), mode='constant', constant_values=0)
.reshape(-1,4)
[:,:2]
.ravel()
)
输出:array([ 2, 4, 9, 10, 12, 2])