问题描述
我有以下Python列表(也可以是元组):
I have the following Python list (can also be a tuple):
myList = ['foo', 'bar', 'baz', 'quux']
我可以说
>>> myList[0:3]
['foo', 'bar', 'baz']
>>> myList[::2]
['foo', 'baz']
>>> myList[1::2]
['bar', 'quux']
如何我是否明确挑选出其索引没有特定模式的项目?例如,我想选择 [0,2,3]
。或者从1000个项目的非常大的列表中,我想选择 [87,342,217,998,500]
。是否有一些Python语法可以做到这一点?看似如下:
How do I explicitly pick out items whose indices have no specific patterns? For example, I want to select [0,2,3]
. Or from a very big list of 1000 items, I want to select [87, 342, 217, 998, 500]
. Is there some Python syntax that does that? Something that looks like:
>>> myBigList[87, 342, 217, 998, 500]
推荐答案
list( myBigList[i] for i in [87, 342, 217, 998, 500] )
我将答案与python 2.5.2进行了比较:
I compared the answers with python 2.5.2:
-
19.7 usec:
[myBigList [i] for i in [87,342,217,998,500]]
20.6 usec: map(myBigList .__ getitem __,(87,342,217,998,500))
20.6 usec: map(myBigList.__getitem__, (87, 342, 217, 998, 500))
22.7 usec: itemgetter(87,342,217,998,500)(myBigList)
22.7 usec: itemgetter(87, 342, 217, 998, 500)(myBigList)
24.6 usec: list(myBigList [i] for i in [87,342,217,998,500])
24.6 usec: list( myBigList[i] for i in [87, 342, 217, 998, 500] )
请注意,在Python 3中,第1个更改为与第4个相同。
Note that in Python 3, the 1st was changed to be the same as the 4th.
另一种选择是从 numpy.array
开始,它允许通过列表进行索引或 numpy.array
:
Another option would be to start out with a numpy.array
which allows indexing via a list or a numpy.array
:
>>> import numpy
>>> myBigList = numpy.array(range(1000))
>>> myBigList[(87, 342, 217, 998, 500)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: invalid index
>>> myBigList[[87, 342, 217, 998, 500]]
array([ 87, 342, 217, 998, 500])
>>> myBigList[numpy.array([87, 342, 217, 998, 500])]
array([ 87, 342, 217, 998, 500])
元组
与切片的工作方式不同。
The tuple
doesn't work the same way as those are slices.
这篇关于从Python列表或元组中明确选择项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!