Python 带键和区域设置的列表排序列表(此处:德语umlauts)
我知道如何使用(简单)key=函数自定义排序。但是如果我需要一个更复杂的key=function,该怎么做呢。我很难把它组合起来Python 带键和区域设置的列表排序列表(此处:德语umlauts),python,python-3.x,Python,Python 3.x,我知道如何使用(简单)key=函数自定义排序。但是如果我需要一个更复杂的key=function,该怎么做呢。我很难把它组合起来 import locale import operator locale.setlocale(locale.LC_ALL, "") # on my computer: German_Germany.1252 lastnames = ["Bange", "Änger", "Amman", "Änger", "Zelch", "Ösbach"] print(sorte
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.
以下是片段:
在第一个示例中,我使用key=locale.strxfrm,这就足够了。第二个示例使用另一个key=function(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.
有什么提示吗?在连续、转换和排序的密钥上使用strxfrm:
f = operator.itemgetter(2,0,1)
print(sorted(lastnames_firstnames_groups, key=lambda x: locale.strxfrm(' '.join(str(y) for y in f(x)))))
听起来你可能想
print(
sorted(
lastnames_firstnames_groups,
key=lambda t: (t[2], strxfrm(t[0]), strxfrm(t[1]))
)
)
这对示例有效,但如果您还有多位数组号,则不起作用。