Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating two lists for filtering

I have 2 lists and I am trying to filter the second list based on a condition in the first list.

list1 = [ {'type': 'A', 'name': '1'},{'type': 'B', 'name': '2'},{'type': 'A', 'name': '3'}]
list2 = [100, 200, 300]

filtered_list1 = list(filter(lambda x: (x['type'] == 'A'), list1))
filtered_list2 = list(filter(lambda x: ??????????????????, list2))

# expected output
# filtered_list1 = [ {'type': 'A', 'name': '1'},{'type': 'A', 'name': '3'}]
# filtered_list2 = [100, 300]

I need to filter elements in list2 based on a condition in list1. How can I iterate over two lists? Or is it possible to use an index with filter/lambda?

like image 576
Gangaraju Avatar asked Sep 01 '25 03:09

Gangaraju


1 Answers

Use zip to visit the corresponding list elements in pairs. You can then unpack the zipped pairs inside a conditional list comprehension, and you're done:

filtered_list2 = [ y for (x, y) in zip(list1, list2) if x["type"] == "A" ]
like image 134
alexis Avatar answered Sep 02 '25 17:09

alexis