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?
>Solution :
words = ["banana apple", "cat elephant dog"]
s = [' '.join(sorted(word.split(' '))) for word in words]
print(s)
#['apple banana', 'cat dog elephant']