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 ordering.
How can I do this?
ordered = [item for item in ordered if item in unordered]
This method creates a new list based on the old ones using Python's list comprehension.
For large amounts of data, turning the unordered list into a set first, as people suggested in comments, makes a huge difference in performance, eg:
unordered = set(unordered)
ordered : 5000 items, unordered : 1000 items
0.09561s without set
0.00042s with set
For 10/2 items the time is almost the same, so it's good to always use a set, no matter what the data size is.
Better use a set for testing membership, like this:
ordered = ['salat', 'baguette', 'burger', 'pizza']
unordered = ['pizza', 'burger']
unord = set(unordered)
ordered = [e for e in ordered if e in unord]
Something like this:
ordered = list(filter(lambda x: x not in unordered, ordered))
The list
function is unnecessary if using Python < 3.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.