如果我有一个列表test
test = [i for i in range(20)]
print(test)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]我想要每5个数字得到最后3个数字,这样我就可以得到一个列表,如下所示:
[2, 3, 4, 7, 8, 9, 12, 13, 14, 17, 18, 19]有没有办法通过列表切片来做到这一点呢?我可以用模函数来做这件事,比如
[i for i in test if i % 5 > 1]但是我想知道是否有一种方法可以通过列表切片来做到这一点?谢谢
发布于 2018-06-16 03:44:36
使用filter函数:
list(filter(lambda x: x % 5 > 1, test)) # [2, 3, 4, 7, 8, 9, 12, 13, 14, 17, 18, 19]发布于 2018-06-16 03:59:02
如果顺序无关紧要,您可以尝试以下操作:
test[2::5] + test[3::5] + test[4::5]或者更一般地说
start = 2 #Number of indices to skip
n = 5
new_test = []
while start < 5:
b.extend(test[start::n])
start += 1发布于 2018-06-16 04:23:35
是的,但我非常怀疑它是否会比简单的列表理解更快:
from itertools import chain, zip_longest as zipl
def offset_modulo(l, x, n):
sentinel = object()
slices = (l[i::n] for i in range(x, n))
iterable = chain.from_iterable(zipl(*slices, fillvalue=sentinel))
return list(filter(lambda x: x is not sentinel, iterable))
print(offset_modulo(range(20), 2, 5))
# [2, 3, 4, 7, 8, 9, 12, 13, 14, 17, 18, 19]
print(offset_modulo(range(24), 2, 5))
# [2, 3, 4, 7, 8, 9, 12, 13, 14, 17, 18, 19, 22, 23]基本上,这种方法获得表示每个索引i的列表切片,以便i % n >= x。然后,它使用zip和chain将它们展平到输出中。
编辑:
更简单的方法
def offset(l, x, n):
diff = n-x
slices = (l[i:i+diff] for i in range(x, len(l), n))
return list(chain.from_iterable(slices))
offset(range(20), 2, 5)
# [2, 3, 4, 7, 8, 9, 12, 13, 14, 17, 18, 19]
offset(range(24), 2, 5)
# [2, 3, 4, 7, 8, 9, 12, 13, 14, 17, 18, 19, 22, 23]在那里我们得到我们想要的相邻元素的切片,然后将它们chain在一起。
https://stackoverflow.com/questions/50881755
复制相似问题