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?
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" ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With