[英]Python sort a list of objects/dictionaries with a given sortKey function
(I use Python 2 here) (我在这里使用Python 2)
I have a list of dictionaries, say 比方说,我有一个词典列表
dei = [{'name': u'Thor'}, {'name': u'Œdipus'}, {'name': u'Creon'}]
I would like to sort that list by their 'name'
attribute. 我想按照
'name'
属性对该列表进行排序。 This is easily done so: 这很容易做到:
dei.sort(key=lambda d: d['name'])
Now, because Python's alphabetical sorting is ASCII-driven, the result will be 现在,因为Python的字母排序是ASCII驱动的,结果将是
[{'name': u'Creon'}, {'name': u'Thor'}, {'name': u'Œdipus'}]
while I'd like Œdipus to be between Creon and Thor. 虽然我希望Œdipus介于Creon和Thor之间。
Following this suggestion , I use PyICU's collator.getSortKey()
function (let's rename it sortKey()
for readability), which works this way on a list strings
of strings: 按照这个建议 ,我使用PyICU的collator.getSortKey
collator.getSortKey()
函数(让它重命名为sortKey()
以便于阅读),它以strings
的列表strings
的形式工作:
strings.sort(key=sortKey)
My problem here: as I cannot modify the sortKey()
function anyhow, how can I use it to sort a list of more complex objects (here, dictionaries) according to some attribute? 我的问题在这里:因为我无论如何都无法修改
sortKey()
函数,如何根据某些属性使用它来排序更复杂的对象(这里是字典)列表?
The only way I found for the moment is by extracting the values of the dictionary in a separate list, sorting it, then implementing a custom compare(a, b)
function returning −1, 0 or 1 depending on the index of a
and b
in the separate list, and calling sort()
with this compare()
function: 我目前找到的唯一方法是在单独的列表中提取字典的值,对其进行排序,然后实现自定义
compare(a, b)
函数,根据a
和b
的索引返回-1,0或1在单独的列表中,并使用此compare()
函数调用sort()
:
names = sorted([d['name'] for d in dei], key=sortKey)
def compare(a, b):
if names.index(a) < names.index(b):
return -1
elif names.index(a) > names.index(b):
return 1
else:
return 0
results = dei.sort(key=lambda d: d['name'], cmp=compare)
which I don't find very elegant. 我觉得不是很优雅。
You can use your own key that internally calls getSortKey
with correct value: 您可以使用自己的密钥在内部调用
getSortKey
并使用正确的值:
>>> import icu
>>> dei = [{'name': u'Thor'}, {'name': u'Œdipus'}, {'name': u'Creon'}]
>>> collator = icu.Collator.createInstance()
>>> dei.sort(key=lambda x: collator.getSortKey(x['name']))
>>> dei
[{'name': 'Creon'}, {'name': 'Œdipus'}, {'name': 'Thor'}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.