Reputation: 359
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?
Upvotes: 0
Views: 904
Reputation: 492
Since you want to sort all the strings in the list, you could use a list comprehension over the items inside your list.
For any item, which is the string you want to sort, split
the item and obtain a list of its words. Then use sorted
to obtain a sorted version of this list.
Finally use join
with " "
to rebuild a string with all its substrings sorted:
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))
Which outputs:
['apple banana', 'cat dog elephant']
This being said, your function:
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
has some issues.
The indentation is not uniform.
string_list
is an iterable. You should iterate directly over it, without using indexing.
string_list[i]
is a string. You should apply split
before sorted
. For example, if you have my_string="banana apple"
and apply sorted
directly, you obtain
[' ', 'a', 'a', 'a', 'a', 'b', 'e', 'l', 'n', 'n', 'p', 'p']
Considering the previous issue, the way you use append
is not correct. append
is a list method and it's called this way
list_to_which_append.append(element_to_append)
Moreover, you don't call the method, so in your code, new
is <built-in method append of list object at 0x7fba704d4b80>
(the address is indicative and may vary).
If you want to correct that function, the code is:
def apply_to_list(string_list):
new = []
for item in string_list:
data = sorted(item.split())
new.append(' '.join(data))
return new
Upvotes: -1
Reputation: 1175
words = ["banana apple", "cat elephant dog"]
s = [' '.join(sorted(word.split(' '))) for word in words]
print(s)
#['apple banana', 'cat dog elephant']
Upvotes: 1
Reputation:
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']
Upvotes: 2