简体   繁体   English

python dict按多个值排序排序

[英]python dict key sort by multiple values ranking

Its easy to sort a dict to list by values, but I need to order keys by kind of boosting specific values in correlation to others. 它很容易将字典排序为按值列出,但是我需要通过增强与其他值相关的特定值来对键进行排序。

An example: 一个例子:

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']

The stuff is ordered by 'w', but for 's' we prefer 'bar' over 'foo' if 'w' hits some treshold. 这些东西按“ w”排序,但是对于“ s”,如果“ w”达到某个阈值,我们更喜欢“ bar”而不是“ foo”。 Is this somehow implemented in python, are there any rules to do this or do you know a python library to handle it? 这是以某种方式在python中实现的,是否有任何规则可以执行此操作,或者您知道可以处理的python库?

Its not about learning the features, its about ordering the way I specify - boost or restrict - the values. 它不是关于学习功能,而是关于我指定的方式排序-提高或限制-值。

In Python 2 you can use something along the line of this: 在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'])

and

sorted(x, cmp=compare)

sorted changed in python 3, if you use it see 在python 3中sorted更改,如果使用它,请参见

http://code.activestate.com/recipes/576653-convert-a-cmp-function-to-a-key-function/ http://code.activestate.com/recipes/576653-convert-a-cmp-function-to-a-key-function/

With that complex sorting needs you should look into key or cmp attributes of sorted() . 考虑到复杂的排序需求,您应该查看sorted() keycmp属性。 See Python wiki for the details and examples: http://wiki.python.org/moin/HowTo/Sorting/#Key_Functions 有关详细信息和示例,请参见Python Wiki: http : //wiki.python.org/moin/HowTo/Sorting/#Key_Functions

Use key if importance can be determined based on a single element. 如果可以根据单个元素确定重要性,则使用key If importance is dependent on relation between two elements you will be best using cmp . 如果重要性取决于两个元素之间的关系,则最好使用cmp

No answer helped so far, but solution for me is: 到目前为止,没有答案有帮助,但是对我来说解决方案是:

Every key get a score at the beginning of 1.0 and then for every feature/value I multiply it with sth. 每个键在1.0的开头都得到一个分数,然后为每个功能/值乘以sth。 and at the end I do a normal ordering. 最后我进行正常的订购。

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. 

Thx, for your questions, thoughts and comments. 谢谢您的提问,想法和评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM