Python - 以非正统的方式遍历数组
Python - Iterating through array in an unorthodox manner
我有一个非常奇怪的问题,到目前为止还没有找到答案我在 python 中有一个数组:
array = [1, 2, 3, 4, 5, 6, 7, 8]
当遍历这个时,我想提取 2 个元素并跳过 2 个,
所以结果将是:
result = [1, 2, 5, 6]
这是怎么做到的?如果不对它进行可怕的修改,我想不出一个好的方法。
使用自定义生成器应该不会太难:
def every2(iterable):
iterable = iter(iterable)
for item in iterable:
# Yield the current item and the next item while advancing the generator
yield item
yield next(iterable)
# Skip the next two elements.
next(iterable)
next(iterable)
这个怎么样:
>>> from itertools import compress, cycle
>>> array = [1, 2, 3, 4, 5, 6, 7, 8]
>>> list(compress(array, cycle([1,1,0,0])))
[1, 2, 5, 6]
我有一个非常奇怪的问题,到目前为止还没有找到答案我在 python 中有一个数组:
array = [1, 2, 3, 4, 5, 6, 7, 8]
当遍历这个时,我想提取 2 个元素并跳过 2 个, 所以结果将是:
result = [1, 2, 5, 6]
这是怎么做到的?如果不对它进行可怕的修改,我想不出一个好的方法。
使用自定义生成器应该不会太难:
def every2(iterable):
iterable = iter(iterable)
for item in iterable:
# Yield the current item and the next item while advancing the generator
yield item
yield next(iterable)
# Skip the next two elements.
next(iterable)
next(iterable)
这个怎么样:
>>> from itertools import compress, cycle
>>> array = [1, 2, 3, 4, 5, 6, 7, 8]
>>> list(compress(array, cycle([1,1,0,0])))
[1, 2, 5, 6]