简体   繁体   English

通过一些属性的总和对python中的对象列表进行排序

[英]Sort a list of objects in python by the sum of some attributes

I've found this question rather helpful in the past, but this time I need to sort some objects in a list by the sum of some of their attributes. 过去,我发现这个问题很有帮助,但是这次我需要根据列表中某些属性的总和对它们进行排序。

Specifically, I have a list of objects each with a dimensions atttribute on 3 axes (eg: obj.dimensions.x) 具体来说,我有一个对象列表,每个对象的尺寸都归因于3个轴(例如:obj.dimensions.x)

I know you can sort a list by one attribute with: 我知道您可以使用以下一种属性对列表进行排序:

list.sort(key=lambda obj: obj.dimensions.x)

But how could I sort it by the sum of the dimensions of each object's three axes such that an object with dimensions 3,3,3 would come before an object with 5,1,1 (greater sum)? 但是,如何对每个对象的三个轴的尺寸之和进行排序,以使尺寸为3、3、3的对象位于具有5、1、1(更大的总和)的对象之前?

Since obj in your example is your entire object, you can do this: 由于示例中的obj是您的整个对象,因此可以执行以下操作:

lst.sort(key=lambda obj: obj.dimensions.x+obj.dimensions.y+obj.dimensions.z)

list is a poor name for a variable, since its also a name of the built-in list() function. list是变量的较差名称,因为它也是内置list()函数的名称。

list.sort(key=lambda obj: obj.dimensions.x + obj.dimensions.y + obj.dimensions.z)

>>> l = [[5,1,1], [3,3,3], [2,1,1], [0,0,0]]
>>> l.sort(key=lambda x: x[0] + x[1] + x[2])
>>> l
[[0, 0, 0], [2, 1, 1], [5, 1, 1], [3, 3, 3]]

This is just an example to show you that you have an access to the item of a list in key function (FYI, in my example l.sort(key=sum) would be more appropriate). 这只是一个示例,向您展示您可以访问键函数中的列表项(FYI,在我的示例中为l.sort(key=sum)更合适)。

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

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