首页 > 解决方案 > How can I case-insensitive sort a 2D List in Python?

问题描述

I have a 2D List like this:

mylist = [[1, "Banana", "description"],[2, "Peach", "description"],[1,"apple", "description"],[2, "orange", "description"]]

I want to sort the list first by the numbers and then by the "name" of the object. But when I sort it with sorted(mylist) I get following output:

mylist=[[1, 'Banana', 'description'], [1, 'apple', 'description'], [2, 'Peach', 'description'], [2, 'orange', 'description']]

Instead, I want a case insensitive sort by the name:

mylist = [[1, 'apple', 'description'], [1, 'Banana', 'description'], [2, 'orange', 'description'], [2, 'Peach', 'description']]

I tried the key key=str.casefold but that doesn't work, as I get following error message:

TypeError: descriptor 'casefold' for 'str' objects doesn't apply to a 'list' object

标签: pythonlistsortingcase-insensitive

解决方案


The items being passed to the key are lists. At the same time, a key can output a sequence such as a tuple or a list, which as you can already see, will be compared lexicographically. That's what is happening when you don't specify a key explicitly.

So a key can transform an input list and return another list:

sorted(mylist, key=lambda row: [row[0], row[1].casefold()])

It is up to you whether you want to do anything with the third element of each row in the key.


推荐阅读