使用键和区域设置对列表列表进行排序(此处:德语元音变音)

2024-03-31

我知道如何使用(简单)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]))
    )
)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用键和区域设置对列表列表进行排序(此处:德语元音变音) 的相关文章