简体   繁体   English

Python:基于字典中存在的值对列表进行排序

[英]Python: sort list based on value present in dictionary

Consider list x = [obj1,obj2,obj3,obj4,obj5] they are grouped in a manner where 考虑列表x = [obj1,obj2,obj3,obj4,obj5]它们按照以下方式分组

obj1.freq = obj2.freq = frequency1 
and 
obj3.freq = obj4.freq = obj5.freq = frequency2 

and I have a dict 我有一个命令

y = {obj1 : 40, obj2 :50, obj3:60, obj4:10, obj5:70, obj6:30, obj7:20}

I have to SORT list x by considering obj of same frequency and sort based on the values of the obj present in dict and my final result should be 我必须通过考虑相同频率的obj来对x进行排序,并根据dict中存在的obj的值进行排序,我的最终结果应该是

x = [obj2,obj1, obj5,obj3,obj4]

1st consider obj1 and obj2 only because they belong to same frequency and sort looking into their values in dict y . 第一,仅考虑obj1obj2因为它们属于相同的频率,并根据dict y对其值进行排序。 obj2 value is 50 and obj1 value is 40 . obj2值为50obj1值为40

so list x now will be sorted such that its 1st element will be obj2 followed by obj1 因此,列表x现在将进行排序,以使其第一个元素为obj2后跟obj1

and i have to do the same for next set of objects belonging to same frequency and sort based on the value present in dict y How do i do it ? 并且我必须对属于同一频率的下一组对象执行相同的操作,并根据dict y中显示的值进行排序。我该怎么做?

Well, I guess you can do it in this way: 好吧,我想您可以通过以下方式做到这一点:

x = [obj1,obj2,obj3,obj4,obj5]
y = {obj1 : 40, obj2 :50, obj3:60, obj4:10, obj5:70, obj6:30, obj7:20}

sorted_list=sorted(lambda e: (e.freq, 0-y[e]), x)

Note, you need 0-y[e] if you want order from bigger values to smaller. 注意,如果要从较大的值到较小的值排序,则需要0-y[e] Normally it can be reached by reverse=True , but in our case it will affect sorting by frequency as well 通常,它可以通过reverse=True到达,但是在我们的例子中,它也会影响按频率排序

This code uses the tuple (frequency, value-in-y) as the sort key; 该代码使用元组(frequency, value-in-y)作为排序键; the list is sorted in reverse order, so that the highest frequency comes first (was not specified in the question, if this is wrong, you can use -i.freq there); 该列表以相反的顺序排序,因此最高的频率排在首位(未在问题中指定,如果这是错误的,则可以在-i.freq使用-i.freq ); objects having frequencies get sorted by the second item in the tuple (the value from dictionary y , if any, or 0: 具有频率的对象按元组中的第二项排序(字典y的值(如果有)或0:

class Obj:
    def __init__(self, name, freq):
        self.freq = freq
        self.name = name

    def __repr__(self):
        return self.name


obj1 = Obj('obj1',42)
obj2 = Obj('obj2',42)
obj3 = Obj('obj3',6)
obj4 = Obj('obj4',6)
obj5 = Obj('obj5',6)
obj6 = Obj('obj6',332)
obj7 = Obj('obj7',123)


x = [obj2, obj1, obj5, obj3, obj4]
y = {obj1:40, obj2:50, obj3:60, obj4:10, obj5:70, obj6:30, obj7:20}

print(sorted(x, key=lambda i: (i.freq, y.get(i, 0)), reverse=True))

Prints 版画

[obj2, obj1, obj5, obj3, obj4]

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

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