Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list of strings by a part of the string

Tags:

I have a list of strings which have the following format:

['variable1 (name1)', 'variable2 (name2)', 'variable3 (name3)', ...] 

... and I want to sort the list based on the (nameX) part, alphabetically. How would I go about doing this?

like image 234
erikfas Avatar asked Jan 29 '14 12:01

erikfas


People also ask

How do you sort a string split in Python?

In this program, we store the string to be sorted in my_str . Using the split() method the string is converted into a list of words. The split() method splits the string at whitespaces. The list of words is then sorted using the sort() method, and all the words are displayed.

How do you find the part of a string in a list Python?

We can also use count() function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list. l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = 'A' count = l1. count(s) if count > 0: print(f'{s} is present in the list for {count} times.

How do you sort a list of strings in Python without sorting?

You can use Nested for loop with if statement to get the sort a list in Python without sort function. This is not the only way to do it, you can use your own logic to get it done.


1 Answers

To change sorting key, use the key parameter:

>>>s = ['variable1 (name3)', 'variable2 (name2)', 'variable3 (name1)'] >>> s.sort(key = lambda x: x.split()[1]) >>> s ['variable3 (name1)', 'variable2 (name2)', 'variable1 (name3)'] >>>  

Works the same way with sorted:

>>>s = ['variable1 (name3)', 'variable2 (name2)', 'variable3 (name1)'] >>> sorted(s) ['variable1 (name3)', 'variable2 (name2)', 'variable3 (name1)'] >>> sorted(s, key = lambda x: x.split()[1]) ['variable3 (name1)', 'variable2 (name2)', 'variable1 (name3)'] >>>  

Note that, as described in the question, this will be an alphabetical sort, thus for 2-digit components it will not interpret them as numbers, e.g. "11" will come before "2".

like image 102
BartoszKP Avatar answered Sep 27 '22 19:09

BartoszKP