Home > Back-end >  Reorder a list based on order from another list of a different length
Reorder a list based on order from another list of a different length

Time:06-14

Given two lists:

listA = ['apples','bananas','peaches','orange']
ListB = ['peaches','apples']

How do I reformat listA so that the items that are in both lists appear in the order from listB.

For example:

Result = ['peaches','bananas','apples','orange']

The rest of the values should maintain their position.

CodePudding user response:

Create an iterator for list B, iterate through list A, if the item occurs in list B, read from the iterator, else use the item as is:

>>> a = ['apples','bananas','peaches','orange']
>>> b = ['peaches','apples']
>>> it_b = iter(b)
>>> [next(it_b) if i in b else i for i in a]
['peaches', 'bananas', 'apples', 'orange']

Optionally: first clean list B to only contain values occurring in list A.

CodePudding user response:

Start with a copy of list_b and insert the missing values at the appropriate places. If you have bigger lists there might be better options concerning the performance.

list_a = ['apples', 'bananas', 'peaches', 'orange']
list_b = ['peaches', 'apples']

result = list_b.copy()

for index, value in enumerate(list_a):
    if value not in list_b:
        result.insert(index, value)

print(result)
  • Related