Home > front end >  How to sort multiple strings inside list alphabetically ascending in Python
How to sort multiple strings inside list alphabetically ascending in Python

Time:02-02

I'd like to write a function which can return the sorted strings inside a list by alphabetically ascending. Like it should turn

["banana apple", "cat elephant dog"] 

into

["apple banana", "cat dog elephant"].

I tried:

def apply_to_list(string_list):
   new = []
   for i in [0,len(string_list)-1]:
    data = sorted(string_list[i])
    new = data.append
    print(new)
    return new

It turned out to be wrong. I know how to sort if the list is simple, I can do:

def sort_words(string):
    words = [word.lower() for word in string.split()]
    words.sort()
    for word in words:
    print(word)
    return 

However, when it comes to several strings inside each of the attribute of a list, my approach failed. Can anyone help?

CodePudding user response:

For each string, you can use str.split to get individual words sorted to sort the words join to join back the words into a single string in a list comprehension:

[' '.join(sorted(x.split())) for x in lst]

Output:

['apple banana', 'cat dog elephant']

CodePudding user response:

words = ["banana apple", "cat elephant dog"] 

s = [' '.join(sorted(word.split(' '))) for word in words]
print(s)

#['apple banana', 'cat dog elephant']

CodePudding user response:

foo = ["banana apple", "cat elephant dog"] 

def apply_to_list(myList):
    return [ ' '.join(sorted(item.split())) for item in myList ]
    
print(apply_to_list(foo))

output

['apple banana', 'cat dog elephant']
  •  Tags:  
  • Related