简体   繁体   中英

How to sort a 3d array by multiple keys

I need to sort a 3d array by multiple keys, and i'm not familiar with lambda. I have an array:

arry = [,
    [[3,1,2], 'foo', 'bar'],
    [[1,2,3], 'foo', 'bar'],
    [[2,1,3], 'foo', 'bar']

    #[[x,y,z], 'blah', 'blah']
]

And i need to sort it so that the z value is highest , but if the z values equal, to sort by the y value lowest , and if y is equal, sort by x lowest . So the output array should look like this:

arry = [
    [[2,1,3], 'foo', 'bar'],
    [[1,2,3], 'foo', 'bar'],
    [[3,1,2], 'foo', 'bar']

    #[[x,y,z], 'blah', 'blah']
]

Use sorted with key :

sorted(arr, key=lambda x:(-x[0][2], x[0][1], x[0][0]))

Output:

[[[2, 1, 3], 'foo', 'bar'],
 [[1, 2, 3], 'foo', 'bar'],
 [[3, 1, 2], 'foo', 'bar']]

Note the - sign on x[0][2] to implement different criteria of comparison.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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