Home > Net >  How can I sort a list by matching the words of another list?
How can I sort a list by matching the words of another list?

Time:10-15

I have two lists of strings like this:

x = ['Apple', 'Banana', 'Coconut']
y = ['Banana', 'Coconut', 'Apple']

How can I sort the Y-list so that it matches the order of the X-list by matching the words to get the following output:

y = ['Apple', 'Banana', 'Coconut']

Can I also make it so that if the Y-list is not equally long as the X-list, it would still sort the content? Like the following example:

x = ['Apple', 'Banana', 'Coconut']
y = ['Coconut', 'Apple']

#Output
y = ['Apple', 'Coconut']

Thanks beforehand.

CodePudding user response:

Try:

x = ["Apple", "Banana", "Coconut"]
y = ["Coconut", "Apple"]

y.sort(key=x.index)
print(y)

Prints:

['Apple', 'Coconut']

EDIT: The list.index returns zero-based index of first item found in list. So x.index("Coconut") returns 2 and x.index("Apple") returns 0 - so we sort based on that number.

  • Related