Vlad
Vlad

Reputation: 8585

sort list of strings based on the index of particular substring

How can I sort a list of sentences like this:

_list = ["i want to buy a car", 
         "never buy a carpet", 
         "i need to buy more stuff", 
         "i don't want to buy it"]

based on a word that precedes / follows a word "buy"?

One way would be to create additional list, store all words that precede / follow the word "buy" and then sort both lists based on a key from a new list. But is there a way to do it without creating additional list?

Upvotes: 1

Views: 647

Answers (1)

cs95
cs95

Reputation: 402413

You do not need any extra lists. You can call list_.sort with a key=callback:

def foo(x):
    l = x.lower().split()
    return l[l.index('buy') - 1]

list_.sort(key=foo)
# ['never buy a carpet', 'i want to buy a car', 'i need to buy more, ...]

This assumes the word buy exists in each string and that it is not the first word in the string. Additional checks may need to be made, and you can modify foo for that. The function foo returns the word that precedes buy, based on which the list is to be sorted.

Upvotes: 3

Related Questions