To sort a list of lists of strings according to a specific pattern, you can use the sort()
method of the list and supply a lambda function as the key
parameter. The lambda function maps each list element to a modified version of that string based on the pattern, and the sort()
method uses these modified strings to sort the list.
For example, let's say you have a list of lists like this:
main.py100 chars2 lines
You want to sort all the strings in each inner list alphabetically, but you want to ignore the first letter of each string when doing the sorting.
You can achieve this by using a lambda function that strips the first letter of each string before doing the sorting. Here's how you can do this:
main.py53 chars2 lines
This lambda function takes each inner list x
, and for each string s
in that list, it strips the first letter of the string s[1:]
, and sorts the resulting list of modified strings using the built-in sorted()
function. The sort()
method then sorts the outer list my_list
based on the sorted list of modified strings for each inner list.
After running this code, my_list
will be:
main.py84 chars2 lines
As you can see, all the strings in each inner list have been sorted alphabetically, with the first letter ignored.
gistlibby LogSnag