Explicitly select items from a Python list or tuple

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

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]

回答1:

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 "", line 1, in  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.



回答2:

What about this:

from operator import itemgetter itemgetter(0,2,3)(myList) ('foo', 'baz', 'quux')


回答3:

It isn't built-in, but you can make a subclass of list that takes tuples as "indexes" if you'd like:

class MyList(list):      def __getitem__(self, index):         if isinstance(index, tuple):             return [self[i] for i in index]         return super(MyList, self).__getitem__(index)   seq = MyList("foo bar baaz quux mumble".split()) print seq[0] print seq[2,4] print seq[1::2]

printing

foo ['baaz', 'mumble'] ['bar', 'quux']


回答4:

>>> map(myList.__getitem__, (2,2,  
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!