问题描述
我有以下 Python 列表(也可以是元组):
myList = ['foo', 'bar', 'baz', 'quux']
我可以说
>>>我的列表[0:3]['foo', 'bar', 'baz']>>>myList[::2]['foo', 'baz']>>>myList[1::2]['bar', 'quux']如何明确挑选索引没有特定模式的项目?例如,我想选择[0,2,3]
.或者从一个包含 1000 个项目的非常大的列表中,我想选择 [87, 342, 217, 998, 500]
.是否有一些 Python 语法可以做到这一点?看起来像的东西:
list( myBigList[i] for i in [87, 342, 217, 998, 500] )
我将答案与 python 2.5.2 进行了比较:
19.7 usec:
[ myBigList[i] for i in [87, 342, 217, 998, 500] ]
20.6 使用:
map(myBigList.__getitem__, (87, 342, 217, 998, 500))
22.7 使用:
itemgetter(87, 342, 217, 998, 500)(myBigList)
24.6 usec:
list( myBigList[i] for i in [87, 342, 217, 998, 500] )
请注意,在 Python 3 中,第 1 个已更改为与第 4 个相同.
另一种选择是从 numpy.array
开始,它允许通过列表或 numpy.array
进行索引:
tuple
与切片的工作方式不同.
I have the following Python list (can also be a tuple):
myList = ['foo', 'bar', 'baz', 'quux']
I can say
>>> myList[0:3]
['foo', 'bar', 'baz']
>>> myList[::2]
['foo', 'baz']
>>> myList[1::2]
['bar', 'quux']
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] )
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))
22.7 usec:
itemgetter(87, 342, 217, 998, 500)(myBigList)
24.6 usec:
list( myBigList[i] for i in [87, 342, 217, 998, 500] )
Note that in Python 3, the 1st was changed to be the same as the 4th.
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.
这篇关于从列表或元组中显式选择项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!