I have a list of list as follows
list_A = [[0.4,0.9,1,4,8],[9,2,3,7,8],[1,1.5,5,7,8],[5,6,10,2,3]]
I am interested in values that are between a=1
and b=4
, 1 and 4 included.
- How can I select values from
list_A
that are in the range of interest (a and b)? I want to get the following outputlist_B
:
list_B = [[1,4],[2,3],[1,1.5],[2,3]]
- How can I record the index of selected values from from each list of lists of
list_A
? The outputlist_C
should look like below
list_C = [[0,1],[1,2],[0,1],[3,4]]
- How can I select values from
list_D
using index positions defined bylist_C
?
list_D = [[100,200,50,60,50],[5,20,30,45,50],[90,10,30,40,60],[30,40,50,20,10]]
so that my output list_E
look like
list_E = [[100,200],[20,30],[90,10],[20,10]]
What I tried so far:
list_B = [i[a:b] for i in list_A]
But I am not getting the desired output.
CodePudding user response:
Start by building a list of the selected items and their indexes using enumerate
and a filter:
>>> list_A = [[0.4,0.9,1,4,8],[9,2,3,7,8],[1,1.5,5,7,8],[5,6,10,2,3]]
>>> a, b = 1, 4
>>> e = [[(i, n) for i, n in enumerate(x) if a <= n <= b] for x in list_A]
>>> e
[[(2, 1), (3, 4)], [(1, 2), (2, 3)], [(0, 1), (1, 1.5)], [(3, 2), (4, 3)]]
List B is just the items:
>>> [[n for _, n in x] for x in e]
[[1, 4], [2, 3], [1, 1.5], [2, 3]]
List C is just the indices (note that your expected output doesn't match this, but the indices of 1 and 4 are indeed 2 and 3, not 0 and 1):
>>> [[i for i, _ in x] for x in e]
[[2, 3], [1, 2], [0, 1], [3, 4]]
You can build list E by zipping C and D:
>>> list_C = [[i for i, _ in x] for x in e]
>>> list_D = [[100,200,50,60,50],[5,20,30,45,50],[90,10,30,40,60],[30,40,50,20,10]]
>>> [[d[i] for i in c] for c, d in zip(list_C, list_D)]
[[50, 60], [20, 30], [90, 10], [20, 10]]
CodePudding user response:
Similar to Samwise, this is a great use for zip
My solution using comprehensions. If you anticipate having to do this multiple times, you could functionalize it fairly easily and return all your lists in a dictionary, for example.
list_A = [[0.4,0.9,1,4,8],[9,2,3,7,8],[1,1.5,5,7,8],[5,6,10,2,3]]
a, b = 1, 4
# filter out numbers outside of your range
list_B = [[n for n in l if a <= n <=b] for l in list_A]
# use the index() method to get the indices of numbers in your range
list_C = [[l.index(n) for n in l if a <= n <= b] for l in list_A
list_D = [[100,200,50,60,50],[5,20,30,45,50],[90,10,30,40,60],[30,40,50,20,10]]
# zip list_C and list_D and filter via index
list_E = [[D[idx] for idx in C] for C, D in zip(list_C, list_D)]
CodePudding user response:
You could zip
list_A
and list_D
together and extract appropriate values in a list comprehension without the intermediate steps
[[d[i] for i, v in enumerate(a) if 1 <= v <= 4] for a, d in zip(list_A, list_D)]
# [[50, 60], [20, 30], [90, 10], [20, 10]]