Home > Software engineering >  How can I sort a list for sentence alphabetically in python based on 2nd or 3rd word or something li
How can I sort a list for sentence alphabetically in python based on 2nd or 3rd word or something li

Time:10-24

How can I sort a list for sentence alphabetically in python based on 2nd or 3rd word or something like that.

Example:

Input: ["The efgh ijk", "The abcd efgh", "The aab xyz"]
Output: ["The aab xyz", "The abcd efgh", "The efgh ijk"]

CodePudding user response:

lst = ["The efgh ijk", "The abcd efgh", "The aab xyz"]

sort_lst = sorted(lst)

print(sort_lst)

CodePudding user response:

Base title of your question : Sorting based on 2nd or 3rd word

You can use sorted with lambda and split() like below:

(this approach first consider 2nd word then 3rd word)

>>> lst = ["The efgh ijk" ,"The aab wxy", "The abcd efgh", "The aab xyz"]
>>> sorted(lst, key=lambda item: (item.split()[1], item.split()[2]))
['The aab wxy', 'The aab xyz', 'The abcd efgh', 'The efgh ijk']


>>> lst = ["The efgh ijk" ,"The aab wxy", "The abcd efgh", "The aab xyz", "abc efgh xyz"]
>>> sorted(lst, key=lambda item: (item.split()[1], item.split()))
['The aab wxy', 'The aab xyz', 'The abcd efgh', 'The efgh ijk', 'abc efgh xyz']
  • Related