简体   繁体   中英

Sorting: x values increase, y values decrease

How do you sort a list of lists such that the x-values increase, and if 2 x-values are the same, the y-value that is lower takes priority?

For example: [[0, 1], [1, 0], [1, 2], [1, 3]] should be sorted into [[0, 1], [1, 3], [1, 2], [1, 1]].

A way would be to first apply the .sort() function on the list, then compare y values for equal x, but is there a simpler way (using lambda, etc.)

It looks like all the items you're sorting are two-element lists of numeric values, so the following should work. You can specify a key argument to the built-in sorted function, to create sort keys for each item. In this case, the key you want is just the same as the item itself, but with negative y values to flip their ordering.

>>> data = [[0, 1], [1, 0], [1, 2], [1, 3]]
>>> print(sorted(data, key=lambda x: (x[0], -x[1])))
[[0, 1], [1, 3], [1, 2], [1, 0]]

If this doesn't work for some reason (perhaps you've got non-numerics in there somewhere), you can use the same approach, but construct the key function differently to provide appropriate comparators for whatever your data actually looks like.

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