[英]In Python, how do I index a list with another list?
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'].并且 T 最终应该是一个包含 ['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']
T = [L[i] for i in Idx]
If you are using numpy, you can perform extended slicing like that:如果您使用的是 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')
...and is probably much faster (if performance is enough of a concern to to bother with the numpy import) ...而且可能要快得多(如果性能足以让 numpy 导入烦恼)
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]
T = map(lambda i: L[i], Idx)
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:我对这些方法中的任何一种都
Flexlist
,所以我想出了一个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]
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']
You could also use the __getitem__
method combined with map
like the following:您还可以将
__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']
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
我会使用
Dict add
所需的keys
Dict add
到index
My problem: Find indexes of list.我的问题:查找列表的索引。
L = makelist() # Returns a list of different objects
La = np.array(L, dtype = object) # add dtype!
for c in chunks:
L_ = La[c] # Since La is array, this works.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.