Reputation: 458
I am trying to sort the individual elements of a list, but not necessarily the entire list.
Given the following list
L = ['A,X,D' , 'Q,A' , 'A,C,B']
I want to sort the individual elements alphabetically giving so that it looks like the following
L = ['A,D,X' , 'A,Q', 'A,B,C']
I tried
L = sorted(L, key = lambda x: x[0])
Upvotes: 1
Views: 235
Reputation: 4197
You want to sort a list of strings based on each string.
First you need to convert the strings into list, like this:
list_of_lists = [l.split(',') for l in L]
output:
[['A', 'X', 'D'], ['Q', 'A'], ['A', 'C', 'B']]
Then, you want to sort each list:
sorted_lists = [sorted(l) for l in list_of_lists]
output:
[['A', 'D', 'X'], ['A', 'Q'], ['A', 'B', 'C']]
Now that we've sorted each list, we want to convert the inner lists back to string (we can use join
):
list_of_strings = [','.join(l) for l in sorted_lists]
output:
['A,D,X', 'A,Q', 'A,B,C']
Or you can do it all in one line, like this:
sorted_strings = [','.join(sorted(l.split(','))) for l in L]
output:
['A,D,X', 'A,Q', 'A,B,C']
Upvotes: 0
Reputation: 13106
You need to sort each part of the list:
L = ['A,X,D' , 'Q,A' , 'A,C,B']
L2 = [','.join(sorted(x.split(','))) for x in L]
L2
# ['A,D,X', 'A,Q', 'A,B,C']
If you don't use split
, you will be sorting with commas included, which has a lower lexicographic value than alphabetical characters:
sorted(L[0])
# ',', ',', 'A', 'D', 'X'
join
will put the commas back in their original places
Upvotes: 2
Reputation: 71451
You can use str.split
with sorted
:
L = ['A,X,D' , 'Q,A' , 'A,C,B']
new_l = [','.join(sorted(i.split(','))) for i in L]
Output:
['A,D,X', 'A,Q', 'A,B,C']
Upvotes: 3