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?
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
Try this:
#Make sure all lists are numpy arrays.
import numpy as np
idx = np.where((list > 3) & (list < 7))
list2 = list2[idx]
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']
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]
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.