2

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)

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)?

Community
  • 1
  • 1
Greg Zaal
  • 263
  • 3
  • 13

2 Answers2

2

Since obj in your example is your entire object, you can do this:

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.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
1
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).

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195