[英]python dict key sort by multiple values ranking
它很容易將字典排序為按值列出,但是我需要通過增強與其他值相關的特定值來對鍵進行排序。
一個例子:
x = [('key1', {'s': 'foo', 'w': 30}), ('key2', {'s': 'bar', 'w': 26}),
('key3', {'s': 'foo', 'w': 23}), ('key4', {'s': 'bar', 'w': 13})]
result: ['key2', 'key1', 'key3', 'key4']
這些東西按“ w”排序,但是對於“ s”,如果“ w”達到某個閾值,我們更喜歡“ bar”而不是“ foo”。 這是以某種方式在python中實現的,是否有任何規則可以執行此操作,或者您知道可以處理的python庫?
它不是關於學習功能,而是關於我指定的方式排序-提高或限制-值。
在Python 2中,您可以沿此使用:
def compare(item1, item2):
key1, it1 = item1
key2, it2 = item2
if max(it1['w'], it2['w']) > threshold:
return cmp(it1['s'], it2['s'])
else:
return cmp(it1['w'], it2['w'])
和
sorted(x, cmp=compare)
在python 3中sorted
更改,如果使用它,請參見
http://code.activestate.com/recipes/576653-convert-a-cmp-function-to-a-key-function/
考慮到復雜的排序需求,您應該查看sorted()
key
或cmp
屬性。 有關詳細信息和示例,請參見Python Wiki: http : //wiki.python.org/moin/HowTo/Sorting/#Key_Functions
如果可以根據單個元素確定重要性,則使用key
。 如果重要性取決於兩個元素之間的關系,則最好使用cmp
。
到目前為止,沒有答案有幫助,但是對我來說解決方案是:
每個鍵在1.0的開頭都得到一個分數,然后為每個功能/值乘以sth。 最后我進行正常的訂購。
key1['score'] is 1.0
# feature 1
if key['s'] == foo:
score = score * 0.1
else:
score = score * 0.6
# feature 2
... and so on
order keys by score, done.
謝謝您的提問,想法和評論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.