简体   繁体   English

如何在python中根据不同的对象值对对象列表进行排序?

[英]How to sort a list of objects based on different object values in python?

I have a class with several different values. 我有一个有几个不同价值观的课程。 I would like to be able to sort a list of these object by the different values, but I am not sure how to do so. 我希望能够通过不同的值对这些对象的列表进行排序,但我不知道该怎么做。 I would like to be able to sort them for any of the values and for both directions (least to greatest and vice versa). 我希望能够为任何值和两个方向(最少到最大,反之亦然)对它们进行排序。

For example below is a sample class, along with a list of sample objects: 例如,下面是一个示例类,以及一个示例对象列表:

class Sample(object):
    def __init__(self, name, sampleValue1, sampleValue2):
        self.name
        self.value1 = sampleValue1
        self.value2 = sampleValue2

    def __repr__(self):
        return self.name

# creating sample objects for clarification
objectNames = ['A','B','C','D']
values1 = [3,4,1,2]
values2 = [1,4,2,3]
sampleObjects = list()
for i in xrange(4):
    obj = Sample(objectNames[i], values1[i], values2[i])
    sampleObjects.append(obj)

Sorting sampleObjects from each of the objects values should yield what's below. 从每个对象值中对sampleObject进行排序应该产生以下内容。 Sorting should return a list of the objects in the order specified (objects names are used below). 排序应按指定的顺序返回对象列表(下面使用对象名称)。

value1: [C,D,A,B]
value1 reversed: [B,A,D,C]
value2: [A,C,D,B]
value2 reversed: [B,D,C,A]

Python built-in sorted function has signature: Python内置的sorted函数有签名:

sorted(iterable[, cmp[, key[, reverse]]])

and

key specifies a function of one argument that is used to extract a comparison key from each list element key指定一个参数的函数,该函数用于从每个列表元素中提取比较键

For your case: 对于你的情况:

>>> sorted(sampleObjects, key=lambda obj: obj.value1)
[C, D, A, B]
>>> sorted(sampleObjects, key=lambda obj: obj.value2)
[A, C, D, B]

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

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