Python列表每n进行n-2切片

标签 python python-3.x list slice

如果我有一个列表测试

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/

相关文章:

python - Tensorflow 函数打印

python - PyQt5错误消息: 'bool' object has no attribute 'layout_base'

python - 通过python正则表达式忽略ip地址第一个八位字节中的这两个数字(以127或0开头)

java - HashSet 在此实例中是否为性能提供任何附加值?

可选参数验证的python可选参数

python - 用于附加和创建 pandas 数据帧的快速 numpy 数组结构

c# - 获取列表中出现次数最多的前 3 个数字

Java Stream API如何改进表达

python - 将 ipython 设置为 pydev 的解释器

python - 如果没有抛出异常则执行