sort all string in a list of list according to specific pattern in python

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.py
my_list = [['apple', 'banana', 'cherry'], ['amazing', 'array', 'color'], ['python', 'java', 'c++']]
100 chars
2 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.py
my_list.sort(key=lambda x: sorted(s[1:] for s in x))
53 chars
2 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.py
[['cherry', 'banana', 'apple'], ['ray', 'mazing', 'olor'], ['a++', 'ava', 'ython']]
84 chars
2 lines

As you can see, all the strings in each inner list have been sorted alphabetically, with the first letter ignored.

gistlibby LogSnag