问题:在Python中,如何将一个列表与另一个列表建立索引?
我想用这样的另一个列表索引一个列表
L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
Idx = [0, 3, 7]
T = L[ Idx ]
T应该最终是一个包含[‘a’,’d’,’h’]的列表。
有没有比这更好的方法
T = []
for i in Idx:
T.append(L[i])
print T
# Gives result ['a', 'd', 'h']
I would like to index a list with another list like this
L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
Idx = [0, 3, 7]
T = L[ Idx ]
and T should end up being a list containing [‘a’, ‘d’, ‘h’].
Is there a better way than
T = []
for i in Idx:
T.append(L[i])
print T
# Gives result ['a', 'd', 'h']
回答 0
回答 1
如果您使用的是numpy,则可以执行如下扩展切片:
>>> import numpy
>>> a=numpy.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
>>> Idx = [0, 3, 7]
>>> a[Idx]
array(['a', 'd', 'h'],
dtype='|S1')
…并且可能要快得多(如果性能足以影响numpy导入)
If you are using numpy, you can perform extended slicing like that:
>>> import numpy
>>> a=numpy.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
>>> Idx = [0, 3, 7]
>>> a[Idx]
array(['a', 'd', 'h'],
dtype='|S1')
…and is probably much faster (if performance is enough of a concern to to bother with the numpy import)
回答 2
功能方法:
a = [1,"A", 34, -123, "Hello", 12]
b = [0, 2, 5]
from operator import itemgetter
print(list(itemgetter(*b)(a)))
[1, 34, 12]
A functional approach:
a = [1,"A", 34, -123, "Hello", 12]
b = [0, 2, 5]
from operator import itemgetter
print(list(itemgetter(*b)(a)))
[1, 34, 12]
回答 3
T = map(lambda i: L[i], Idx)
T = map(lambda i: L[i], Idx)
回答 4
我对这些方法都不满意,所以我想出了一个Flexlist
类,它允许通过整数,切片或索引列表进行灵活的索引编制:
class Flexlist(list):
def __getitem__(self, keys):
if isinstance(keys, (int, slice)): return list.__getitem__(self, keys)
return [self[k] for k in keys]
例如,您将其用作:
L = Flexlist(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
Idx = [0, 3, 7]
T = L[ Idx ]
print(T) # ['a', 'd', 'h']
I wasn’t happy with any of these approaches, so I came up with a Flexlist
class that allows for flexible indexing, either by integer, slice or index-list:
class Flexlist(list):
def __getitem__(self, keys):
if isinstance(keys, (int, slice)): return list.__getitem__(self, keys)
return [self[k] for k in keys]
Which, for your example, you would use as:
L = Flexlist(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
Idx = [0, 3, 7]
T = L[ Idx ]
print(T) # ['a', 'd', 'h']
回答 5
L= {'a':'a','d':'d', 'h':'h'}
index= ['a','d','h']
for keys in index:
print(L[keys])
我会用一个Dict add
想要keys
的index
L= {'a':'a','d':'d', 'h':'h'}
index= ['a','d','h']
for keys in index:
print(L[keys])
I would use a Dict add
desired keys
to index
回答 6
您也可以将__getitem__
方法与map
以下方法结合使用:
L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
Idx = [0, 3, 7]
res = list(map(L.__getitem__, Idx))
print(res)
# ['a', 'd', 'h']
You could also use the __getitem__
method combined with map
like the following:
L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
Idx = [0, 3, 7]
res = list(map(L.__getitem__, Idx))
print(res)
# ['a', 'd', 'h']