Reputation: 6290
I have a Python list, for example list = [1,2,3,4,5,6,7,8,9]
. In addition, I have another list list2 = ['a','b','c','d','e','f','g','h','j']
. Now I would like to do the following:
idx = (list > 3) & (list < 7)
list2 = list2[idx]
This should yield ['d','e','f']
. Of course, this is not possible with lists. How can this be done with lists?
Upvotes: 3
Views: 75
Reputation: 11183
Option with list comprehension accessing elements by index:
res = [ list2[idx] for idx, e in enumerate(list1) if 7 > e > 3 ]
print(res) #=> ['d', 'e', 'f']
[ [list2[idx], e] for idx, e in enumerate(list1) if 7 > e > 3 ]
#=> [['d', 4], ['e', 5], ['f', 6]]
Then transpose:
res1, res2 = [ list(i) for i in zip(*[ [list2[idx], e] for idx, e in enumerate(list1) if 7 > e > 3 ]) ]
print (res1, res2 ) #=> ['d', 'e', 'f'] [4, 5, 6]
Upvotes: 0
Reputation: 71451
You can use zip
:
l1 = [1,2,3,4,5,6,7,8,9]
l2 = ['a','b','c','d','e','f','g','h','j']
result = [a for a, b in zip(l2, l1) if 3 < b < 7]
Output:
['d', 'e', 'f']
To get the reduced list as well:
result, reduced = map(list, zip(*[[a, b] for a, b in zip(l2, l1) if 3 < b < 7]))
Output:
['d', 'e', 'f'] #result
[4, 5, 6] #reduced
Upvotes: 6
Reputation: 379
Try this:
#Make sure all lists are numpy arrays.
import numpy as np
idx = np.where((list > 3) & (list < 7))
list2 = list2[idx]
Upvotes: 1