Reputation: 11
Trying to choose items from a list by another list of indices by looping over them and choosing them by index, but the result is missing duplicate items .
example.
X = [[1, 'a', 33], [2, 'a', 44], [3, 'bb', 56]] #sample data
indices = [1,1,1] #index with duplicates
[ x[-1] for i,x in enumerate(X) if i in indices]
I expect
[[2, 'a', 44], [2, 'a', 44], [2, 'a', 44]]
but I get
[[2, 'a', 44]]
I tried normal loop instead of comprehnsion and it works. but doesnt work when I try to get part of the list inside. so I want
Upvotes: 1
Views: 28
Reputation: 121
Try this
[mainL[x] for x in indices]
Output:
[[2, 'a', 44], [2, 'a', 44], [2, 'a', 44]]
Upvotes: 0
Reputation: 42746
You want to iterate indices
in the comprehension and pick that element from X
:
>>> X = [[1, 'a', 33], [2, 'a', 44], [3, 'bb', 56]]
>>> indices = [1,1,1]
>>> [X[i] for i in indices]
[[2, 'a', 44], [2, 'a', 44], [2, 'a', 44]]
In your case it do not work because you i
will be 1
only once in the iteration with enumerate
Upvotes: 1