python - python中的复杂列表切片/索引

标签 python list slice

我有一个如下所示的列表:

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

我想生成一个过滤后的列表,如下所示:

filtered_lst = [2, 6, 7, 9, 10, 13]

Python 是否提供自定义切片的约定。比如:

lst[1, 5, 6, 8, 9, 12] # slice a list by index

最佳答案

使用operator.itemgetter() :

from operator import itemgetter

itemgetter(1, 5, 6, 8, 9, 12)(lst)

演示:

>>> from operator import itemgetter
>>> lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
>>> itemgetter(1, 5, 6, 8, 9, 12)(lst)
(2, 6, 7, 9, 10, 13)

这将返回一个元组;如果需要,则使用 list(itemgetter(...)(lst)) 转换为列表。

请注意,这等同于带有一组索引而不是范围的切片表达式 (lst[start:stop]);它不能用作左侧切片赋值 (lst[start:stop] = some_iterable)。

关于python - python中的复杂列表切片/索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14114621/

相关文章:

c - 如何将链表拆分为2个列表?

list - slice 和容器/列表之间的区别

go - 就地截断 slice

python - 切片具有不同长度的子列表

python - PyDev 安装不工作。没有编辑器。没有偏好

c# - C# 中允许在 O(1) 中反转的数据结构

python - CS Circles 部分 7C 编码练习 : One Triangle 中的循环

python - 获取Python列表的当前索引

python - Py2neo 密码查询结果为 _assert_unfinished。有人可以告诉我为什么吗?

python - 读取文件python中的前一行