Jensen
Jensen

Reputation: 13

How to get a sublist of a list based on another list?

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

Answers (4)

Samuel Nde
Samuel Nde

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

jpp
jpp

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

Osman Mamun
Osman Mamun

Reputation: 2882

import numpy as np
a = np.array(a)
b = np.array(b)
c = b[np.where(a>10)]

Upvotes: 0

vash_the_stampede
vash_the_stampede

Reputation: 4606

Zip?

print([[*i] for i in list(zip(a,b)) if i[0] > 10])
[[12, 'a'], [14, 'd']]

Upvotes: 1

Related Questions