简体   繁体   中英

How to sort multiple strings inside list alphabetically ascending in Python

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?

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']
words = ["banana apple", "cat elephant dog"] 

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

#['apple banana', 'cat dog elephant']
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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM