skim8201
skim8201

Reputation: 81

filter out list elements that match another list and preserve the original list order

Lets say i have following list

periods = ['2017 Q1', 'TEST2', '2018 Q4','2017 Q2', '2019Q3', '2017 Q3', '2017 Q4', '2017 FY', 'TEST']

I want to filter on periods to return any elements in the list that contain elements from this list

master_list = ['Q1', 'Q2', 'Q3', 'Q4', 'S1', 'S2', 'FY']

So i would expect

filtered = ['2017 Q1', '2018 Q4','2017 Q2', '2019 Q3', '2017 Q3', '2017 Q4', '2017 FY']

When i do something like this

a = [period for period in periods for master in master_list if period in master]

But this returns:

filtered = ['2017 Q1', '2017 Q2', '2019 Q3', '2017 Q3', '2017 Q4' ,'2018 Q4' ,'2017 FY']

This one has been reordered.

Upvotes: 1

Views: 160

Answers (2)

Nitin Jain
Nitin Jain

Reputation: 307

I am not sure if the resulting list is correct as your condition is (period in master) which would never be True. Why not do something straightforward like:

filtered = []
for period in periods:
  for master in master_list:
    if master in period:
      filtered.append(period)

Upvotes: 0

Dani Mesejo
Dani Mesejo

Reputation: 61910

You need to check if master in period:

master_list = ['Q1', 'Q2', 'Q3', 'Q4', 'S1', 'S2', 'FY']
periods = ['2017 Q1', 'TEST2', '2018 Q4', '2017 Q2', '2019Q3', '2017 Q3', '2017 Q4', '2017 FY', 'TEST']
a = [period for period in periods for master in master_list if master in period]

print(a)

Output

['2017 Q1', '2018 Q4', '2017 Q2', '2019Q3', '2017 Q3', '2017 Q4', '2017 FY']

Explanation

The expression '2017 Q1' in 'Q1' checks if '2017 Q1' is a substring of 'Q1' which is False, on the other hand 'Q1' in '2017 Q1' is True

Upvotes: 2

Related Questions