sree
sree

Reputation: 51

How to sort the list values according to the first letter of the value in Python

I have a issue in lists. I have a list =['randomf','decisiont','extremeg'] which is appended with another list list2 = ['bike','age','car'], and then sorted according it together which means each value of first list have the appended values of list2(e.g:'randomf_bike','randomf_age' ,'randomf_car') but when I sort it turns to be like this(e.g: 'randomf_age','randomf_bike' ,'randomf_car') Its not only sorting according to the first letter of the value but also sorting according to the letter after '_'. How can I sort according to the first letter?

My code: 
list =['randomf','decisiont','extremeg'] 
list2 = ['bike','age','car']
new_list =  [el1+'_'+el2 for el2 in list2 for el1 in sorted(set(list))]
new_list = sorted(new_list)
which gives : new_list = ['decisiont_age','decisiont_bike' ,'decisiont_car','extremeg_age','extremeg_bike' ,'extremeg_car','randomf_age','randomf_bike' ,'randomf_car'] 
The excepted output is:
 new_list = ['decisiont_bike','decisiont_age' ,'decisiont_car','extremeg_bike','extremeg_age' ,'extremeg_car', 'randomf_bike','randomf_age' ,'randomf_car']

Upvotes: 1

Views: 2830

Answers (1)

Blckknght
Blckknght

Reputation: 104752

You can give a key function to the call to sorted. If you want to sort only on the part of the string before the first _ character, you can do sorted(new_list, key=lambda s: s.split('_', 1)[0]).

But you might also be able to avoid that second sort, if you assemble your compound strings in the right order from the start. I think you can just change the order of your two-level iteration and it should match what you want (you're already sorting the first list):

new_list =  [el1+'_'+el2 for el1 in sorted(set(list)) for el2 in list2] # change order here
# don't sort again!

Upvotes: 4

Related Questions