I want to order list1 based on the strings in list2. Any elements in list1 that don't correspond to list2 should be placed at the end of the correctly ordered list1.
For example:
list1 = ['Title1-Apples', 'Title1-Oranges', 'Title1-Pear', 'Title1-Bananas']
list2 = ['Bananas', 'Oranges', 'Pear']
list1_reordered_correctly= ['Title1-Bananas','Title1-Oranges','Title1-Pear','Title1-Apples']
Here's an idea:
>>> def keyfun(word, wordorder):
... try:
... return wordorder.index(word)
... except ValueError:
... return len(wordorder)
...
>>> sorted(list1, key=lambda x: keyfun(x.split('-')[1], list2))
['Title1-Bananas', 'Title1-Oranges', 'Title1-Pear', 'Title1-Apples']
To make it neater and more efficient (index has to traverse the list to find the right item), consider defining your word-order as a dictionary, i.e.:
>>> wordorder = dict(zip(list2, range(len(list2))))
>>> wordorder
{'Pear': 2, 'Bananas': 0, 'Oranges': 1}
>>> sorted(list1, key=lambda x: wordorder.get(x.split('-')[1], len(wordorder)))
['Title1-Bananas', 'Title1-Oranges', 'Title1-Pear', 'Title1-Apples']
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