简体   繁体   English

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

[英]Complex list slice/index in 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]

Does Python provide a convention for custom slicing. Python是否提供自定义切片的约定。 Something such as: 像这样的东西:

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

Use operator.itemgetter() : 使用operator.itemgetter()

from operator import itemgetter

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

Demo: 演示:

>>> 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)

This returns a tuple; 这会返回一个元组; cast to a list with list(itemgetter(...)(lst)) if a that is a requirement. 如果这是一个要求,则转换为带有list(itemgetter(...)(lst))

Note that this is the equivalent of a slice expression ( lst[start:stop] ) with a set of indices instead of a range; 请注意,这相当于切片表达式( lst[start:stop] ),其中包含一组索引而不是范围; it can not be used as a left-hand-side slice assignment ( lst[start:stop] = some_iterable ). 它不能用作左侧切片赋值( lst[start:stop] = some_iterable )。

Numpy arrays have this kind of slicing syntax: Numpy数组有这种切片语法:

In [45]: import numpy as np

In [46]: lst = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])

In [47]: lst[[1, 5, 6, 8, 9, 12]]
Out[47]: array([ 2,  6,  7,  9, 10, 13])

I'd go with the operator.itemgetter() method that Martijn Pieters has suggested, but here's another way (for completeness) 我会选择Martijn Pieters建议的operator.itemgetter()方法,但这是另一种方式(为了完整性)

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

In [24]: indices = set([1, 5, 6, 8, 9, 12])

In [25]: [n for i,n in enumerate(lst) if i in indices]
Out[25]: [2, 6, 7, 9, 10, 13]

It's easily and straightforwardly done using a list comprehension. 使用列表理解可以轻松直接地完成。

lst = range(1, 14)
indices = [1, 5, 6, 8, 9, 12]
filtered_lst = [lst[i] for i in indices]

A Python slice allows you to make the slice the target of an assignment. Python切片允许您将切片作为赋值的目标。 And the Python slicing syntax does not allow for slices with irregular patterns of indices. 并且Python切片语法不允许具有不规则索引模式的切片。 So, if you want to make your "custom" slice the target of an assignment, that's not possible with Python slice syntax. 因此,如果您希望将“自定义”切片作为赋值的目标,那么使用Python切片语法是不可能的。

If your requirements are met by taking a copy of the specified elements, then operator.itemgetter() meets your needs. 如果通过获取指定元素的副本来满足您的要求,则operator.itemgetter()满足您的需求。 If you need slice assignment, then numpy slices are a good option. 如果你需要切片分配,那么numpy切片是一个不错的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM