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?
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.
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.
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.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With