从列表或元组中明确选择项目 [英] Explicitly select items from a list or tuple

查看:52
本文介绍了从列表或元组中明确选择项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下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微秒:[ 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微秒:itemgetter(87, 342, 217, 998, 500)(myBigList)

24.6微秒: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])

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

The tuple doesn't work the same way as those are slices.

这篇关于从列表或元组中明确选择项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆