Kit*_*Kit 103 python indexing select tuples list
我有以下Python列表(也可以是一个元组):
myList = ['foo', 'bar', 'baz', 'quux']
Run Code Online (Sandbox Code Playgroud)
我可以说
>>> myList[0:3]
['foo', 'bar', 'baz']
>>> myList[::2]
['foo', 'baz']
>>> myList[1::2]
['bar', 'quux']
Run Code Online (Sandbox Code Playgroud)
如何明确选择索引没有特定模式的项目?例如,我想选择[0,2,3].或者从1000个项目的非常大的列表中,我想选择[87, 342, 217, 998, 500].是否有一些Python语法可以做到这一点?看起来像:
>>> myBigList[87, 342, 217, 998, 500]
Run Code Online (Sandbox Code Playgroud)
Dan*_* D. 130
list( myBigList[i] for i in [87, 342, 217, 998, 500] )
Run Code Online (Sandbox Code Playgroud)
我将答案与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] )
请注意,在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])
Run Code Online (Sandbox Code Playgroud)
这tuple与切片的工作方式不同.
Mar*_*cin 39
那这个呢:
from operator import itemgetter
itemgetter(0,2,3)(myList)
('foo', 'baz', 'quux')
Run Code Online (Sandbox Code Playgroud)
它不是内置的,但如果您愿意,可以创建一个列表的子类,将元组作为"索引":
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]
Run Code Online (Sandbox Code Playgroud)
印花
foo
['baaz', 'mumble']
['bar', 'quux']
Run Code Online (Sandbox Code Playgroud)
也许列表理解是按顺序进行的:
L = ['a', 'b', 'c', 'd', 'e', 'f']
print [ L[index] for index in [1,3,5] ]
Run Code Online (Sandbox Code Playgroud)
产生:
['b', 'd', 'f']
Run Code Online (Sandbox Code Playgroud)
那是您要找的东西吗?
>>> map(myList.__getitem__, (2,2,1,3))
('baz', 'baz', 'bar', 'quux')
Run Code Online (Sandbox Code Playgroud)
您还可以创建自己的List类,__getitem__如果您希望能够这样做,则支持元组作为参数myList[(2,2,1,3)].
| 归档时间: |
|
| 查看次数: |
252470 次 |
| 最近记录: |