本文介绍了python中的复杂列表切片/索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个看起来像这样的列表:
I have a list that looks like this:
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
我想生成一个过滤列表,如下所示:
I'd like to generate a filtered list that looks like this:
filtered_lst = [2, 6, 7, 9, 10, 13]
Python是否提供自定义切片的约定.诸如此类的东西:
Does Python provide a convention for custom slicing. Something such as:
lst[1, 5, 6, 8, 9, 12] # slice a list by index
推荐答案
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))
强制转换为列表.
This returns a tuple; cast to a list with list(itemgetter(...)(lst))
if a that is a requirement.
请注意,这等效于带有一组索引而不是范围的切片表达式(lst[start:stop]
);不能用作左侧切片分配(lst[start:stop] = some_iterable
).
Note that this is the equivalent of a slice expression (lst[start:stop]
) with a set of indices instead of a range; it can not be used as a left-hand-side slice assignment (lst[start:stop] = some_iterable
).
这篇关于python中的复杂列表切片/索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!