Python: removing entries from an ordered list that are not in an unordered list

I have two lists:

ordered = ['salat', 'baguette', 'burger', 'pizza'] unordered = ['pizza', 'burger'] 

Now I want to remove all entries from the ordered list that are not in the unordered list, while preserving the order.

How can i do this?

+4
source share
3 answers
 ordered = [item for item in ordered if item in unordered] 

This method creates a new list based on old ones using Python list comprehension.

For large amounts of data, turning an unordered list into a set first, as the people suggested in the comments, is of utmost importance in performance, for example:

 unordered = set(unordered) 

Benchmark!

ordered: 5000 items, unordered: 1000 items
0.09561 s without dial 0.00042 with setting

For 10/2 elements, the time is almost the same, therefore it is useful to always use a set, regardless of the size of the data.

+9
source

Better use a membership testing kit, for example:

 ordered = ['salat', 'baguette', 'burger', 'pizza'] unordered = ['pizza', 'burger'] unord = set(unordered) ordered = [e for e in ordered if e in unord] 
+2
source

Something like that:

 ordered = list(filter(lambda x: x not in unordered, ordered)) 

The list function is not needed if you use Python <3.

0
source

Source: https://habr.com/ru/post/1395982/


All Articles