python - 使用键和区域设置对列表进行排序(此处为 : german umlauts)

标签 python python-3.x

我知道如何使用(简单的)key=function 自定义排序。但如果我需要一个更复杂的 key= 函数,该怎么做呢?我在将它们组合在一起时遇到问题。

这是片段: 在第一个示例中,我使用 key=locale.strxfrm,这足以满足此目的。第二个例子我使用另一个 key= 函数(itemgetter)。但我需要两者一起。

import locale
import operator

locale.setlocale(locale.LC_ALL, "")
# on my computer: German_Germany.1252

lastnames = ["Bange", "Änger", "Amman", "Änger", "Zelch", "Ösbach"]
print(sorted(lastnames, key=locale.strxfrm)) # sorted correct
                                             # alphabetically for Germany
print()

lastnames_firstnames_groups =[
    ["Bange", "Michael", 2],
    ["Änger", "Ämma", 2],
    ["Amman", "Anton", 1],
    ["Änger", "Chris", 2],
    ["Zelch", "Sven", 1],
    ["Ösbach", "Carl", 1]
]
print(sorted(lastnames_firstnames_groups, key=operator.itemgetter(2,0,1)))
# The result is sorted as I expected (the german umlaute are NOT sorted
# the correct way). Is there a way to "add" the string tranformation strxfrm
# as in the first example to this. 

有什么提示吗?

最佳答案

听起来你可能想要

print(
    sorted(
        lastnames_firstnames_groups,
        key=lambda t: (t[2], strxfrm(t[0]), strxfrm(t[1]))
    )
)

关于python - 使用键和区域设置对列表进行排序(此处为 : german umlauts),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25056907/

相关文章:

python - 为什么当我按下 ctrl-c 时 Tornado 会花这么长时间才能死掉?

python - pyperclip 没有属性副本

python - 将列表分配给构造函数

python-3.x - python 3 : Convert wave data (byte array) to numpy array of floating point values

python - 将 NumPy np.uint8 数组列表转换为 np.unicode_ 数组

python - 用于存储游戏 map 的列表或字典

python - Tkinter 在框架中加载图像

python - 尝试使用变量更改 discord.Colour 时错误请求 400

Python:无法使用 beautifulsoup 获得任何输出

python-3.x - python TLS套接字中的TLS session 恢复