python - 从列表或元组中显式选择项目

标签 python list select indexing tuples

我有以下 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]

最佳答案

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 进行索引:

>>> 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 的工作方式与切片不同。

关于python - 从列表或元组中显式选择项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6632188/

相关文章:

Python 3.3 : Is it possible to put unicode characters on buttons with tkinter?

应用 groupby 和大小后,Python pandas 访问 True 和 False 值

Python 在达到某个点时停止迭代

php - Mysql ORDER BY 数字 DESC

python - 如何从python中的字符串获取索引位置而不产生重复结果

python - 如何在Django网页中显示excel文件

python - 来自锯齿状数组的数据帧

javascript - 改变jquery中的li类

mysql - SQL 查询 - 在一列上区分其他列的不同值(使用 INNER JOIN)

php - 比较三个字段