-1

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
Taxogatl
  • 21
  • 3
  • 3
    If you make those actually strings, then people can give executable examples. And please don't call variables `list` as it shadows the `list()` function. If you really don't have a better name, call it `list_` – Martin Thoma Aug 14 '20 at 21:23
  • @MartinThoma. Excellent advice. I think `mylist` is the most common version I see for toy examples. – Mad Physicist Aug 14 '20 at 21:25
  • 1
    The syntax of your examples is wrong so you clearly haven’t executed these - always try examples yourself before putting ‘code’ into a question – DisappointedByUnaccountableMod Aug 14 '20 at 21:36
  • You really should fix up your question. It's a good question, but will likely keep getting downvoted if you don't. – Mad Physicist Aug 14 '20 at 23:24

1 Answers1

1

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.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264