NeutronStar
NeutronStar

Reputation: 2157

List comprehension on two lists

Let's say I have two equal-length lists, list1 and list2, both consisting of a bunch of numbers. I want to remove all the elements of list1 that don't meet a certain criterion. Simple enough. How would I also remove the corresponding elements from list2 though? If I remove, say, the 5th element of list1, I would also like to remove the 5th element of list2. Example of what I'm trying to do below:

list1 = [i for i in list1 if i >= 1]
list2 = list2 #but with the corresponding values of list1 removed from list2 as well

I could come up with, say,

list2_temp = []
for j in range(len(list1)):
    if list1[j] >= 1:
        list2_temp.extend(list2[j])

list1 = [i for i in list1 if i >= 1]

but I am looking for a more "Pythonic" way to do it, specifically if there is any way I can use list comprehensions on list2 as well as list1. Any ideas/suggestions?

Upvotes: 0

Views: 3349

Answers (2)

mgilson
mgilson

Reputation: 310287

I think that maybe the problem is that you have 2 parallel lists rather than a single list that holds items which have the all the data for each element.

Think of the data as a spreadsheet -- Currently you have 2 columns and you want to filter the rows by the values in one column. Rather than modeling the data as a bunch of columns, it's better to model it as a list of rows.

To fix the problem now you can zip the lists together, filter them and then unzip at the end:

items = [(i, j) for i, j in zip(list1, list2) if i >= 1]
tuple1, tuple2 = zip(*items)

but I still recommend considering storing the data in a different way...

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799520

Combine, filter, split:

list1[:], list2[:] = zip(*((x, y) for (x, y) in zip(list1, list2) if predicate(x)))

Upvotes: 4

Related Questions