从列表或元组中明确选择项目

2024-05-19 15:39:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下Python列表(也可以是元组):

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语法可以做到这一点吗?看起来像:

>>> myBigList[87, 342, 217, 998, 500]

Tags: 项目列表foo模式语法barbaz元组
3条回答

这个呢:

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

它不是内置的,但是如果您愿意,可以创建一个子类list,它将元组作为“索引”:

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]

印刷

foo
['baaz', 'mumble']
['bar', 'quux']
list( myBigList[i] for i in [87, 342, 217, 998, 500] )

我将答案与Python2.5.2进行了比较:

  • 19.7用途:[ 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用途:list( myBigList[i] for i in [87, 342, 217, 998, 500] )

注意,在Python 3中,第一个更改为与第四个相同。


另一种选择是从numpy.array开始,它允许通过列表或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])

tuple的工作方式与切片不同。

相关问题 更多 >