如果我有一个列表测试
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]
但是我想知道是否有办法通过列表切片来做到这一点?谢谢
最佳答案
使用filter功能:
list(filter(lambda x: x % 5 > 1, test)) # [2, 3, 4, 7, 8, 9, 12, 13, 14, 17, 18, 19]
关于Python列表每n进行n-2切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50881755/