Reputation: 2263
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']
Upvotes: 216
Views: 277327
Reputation: 700
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.
Upvotes: 1
Reputation: 8318
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']
Upvotes: 6
Reputation: 11
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
Upvotes: 1
Reputation: 180512
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]
Upvotes: 12
Reputation: 30250
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']
Upvotes: 12
Reputation: 43680
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)
Upvotes: 56