gpt4 book ai didi

python - 使用键和语言环境对列表列表进行排序(此处为 : german umlauts)

转载 作者:太空宇宙 更新时间:2023-11-04 01:15:15 25 4
gpt4 key购买 nike

我知道如何使用(简单的)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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com