python - 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
解决方案
The items being passed to the key are list
s. 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.
推荐阅读
- c# - Microsoft excel 互操作中的 Excel 工作表。将图像保存到文件
- python - 与 Tkinter 的鼠标单击事件绑定似乎比预期慢一步
- python - 如何在 Mongo shell 中用 null 替换 NaN?
- linux - MTU 对带宽/吞吐量的影响
- flutter - 如何在 Flutter 的 StreamBuilder 中添加搜索选项?
- python - 如何在 Meta django 类中获取会话变量?
- python - 如何使用 SQLAlchemy 编写带有 IN 子句的更新查询,其效率与普通 SQL 相同
- javascript - 如何让 tspan 继承父文本 x?(在文本中定位多行 tspan)
- c++ - 为什么我们需要定义一个类的静态变量,而不像类的其他成员?
- c++ - 为什么这个链表会在 for 循环中引发分段错误?