Home > Blockchain >  use threshold on a list of numbers to subset corresponding elements from other list of objects
use threshold on a list of numbers to subset corresponding elements from other list of objects

Time:02-02

I have two lists of lists which share the same dimension (same length, each list in the list have the same number of elements)

list1 looks like this:

list1 = [[1,2,3],[2,3,4],[4,5,2],[4,0,9]]

list2 looks like this:

list2 = [['a''b','c'],['a','d','e'],['a','f','b'],['p','o','a']]

let's say I have a threshold x = 3

I want to filter out elements from list 2 which have the same position of those elements in list1 which fall below x = 3

so for instance for x = 3 I would want to obtain:

list3 = [[],['e'],['a','f'],['p','a']

how can I do so?

thank you for your help

CodePudding user response:

You can use zip to walk the two lists (and sublists) together and filter the values in list2 that satisfy the condition in the corresponding position in list1:

out = [[j for i, j in zip(li1, li2) if i>3] for li1, li2 in zip(list1, list2)]

Output:

[[], ['e'], ['a', 'f'], ['p', 'a']]

CodePudding user response:

I would use the Python zip function to "merge" the two lists.

list1 = [[1,2,3],[2,3,4],[4,5,2],[4,0,9]]
list2 = [['a','b','c'],['a','d','e'],['a','f','b'],['p','o','a']]

threshold = 3

list3 = [
    [char for value, char in zip(sub_one, sub_two) if value > threshold]
    for sub_one, sub_two in zip(list1, list2)
]

print(list3)

This outputs

[[], ['e'], ['a', 'f'], ['p', 'a']]

The outer zip merges list1 and list2 into:

[([1, 2, 3], ['a', 'b', 'c']),
 ([2, 3, 4], ['a', 'd', 'e']),
 ([4, 5, 2], ['a', 'f', 'b']),
 ([4, 0, 9], ['p', 'o', 'a'])]

while the inner zip merges e.g. [1,2,3] and ['a','b','c'] into [(1, 'a'), (2, 'b'), (3, 'c')]. Then, the inner list comprehension can use a simple filtering with if value > threshold.

  •  Tags:  
  • Related