Reputation: 13
a = [12,3,8,14]
b = ['a','b','c','d']
I want to find the sublist of elements in b
so that the corresponding item in a
is greater than 10
:
b_even = [b[i] for i, e in enumerate(a) if e > 10]
This code works OK, but are there any easier ways like b[a>10]
in R?
Upvotes: 1
Views: 117
Reputation: 2753
My first choice would have been what you have but I could get the same results using;
[s[1] for s in zip(a, b) if s[0] > 10]
Upvotes: 0
Reputation: 164843
The regular solution is to use zip
:
res = [i for i, j in zip(a, b) if j > 10]
A functional alternative is possible via operator.itemgetter
and enumerate
:
from operator import itemgetter
res = itemgetter(*(idx for idx, val in enumerate(a) if val > 10))(b)
For vectorised functionality / syntax, you can use a 3rd party library such as NumPy.
Upvotes: 1
Reputation: 2882
import numpy as np
a = np.array(a)
b = np.array(b)
c = b[np.where(a>10)]
Upvotes: 0
Reputation: 4606
Zip?
print([[*i] for i in list(zip(a,b)) if i[0] > 10])
[[12, 'a'], [14, 'd']]
Upvotes: 1