-1

For instance, I have a list like:

[[1,1,0],[1,0,1],[0,0,0]]

first to sort the first element, and then if the first element are same, sort the second element, and then if the second elements are same sort for third, forth.... the result should like this:

[[0,0,0],[1,0,1],[1,1,0]]

obviously, the sorted function cannot solve this problem easily even if use key=...

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
zzy
  • 113
  • 2

1 Answers1

7

sorted() solves this out of the box, because list objects are compared lexicographically. That is, two lists are ordered based on the first element that differs between them.

Your desired sort output is the default when not using a key:

>>> sorted([[1, 1, 0], [1, 0, 1], [0, 0, 0]])
[[0, 0, 0], [1, 0, 1], [1, 1, 0]]

From the Comparisons section of the Python reference documentation:

Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.

If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is ordered first (for example, [1,2] < [1,2,3]).

The key function is not limited to returning single elements either, it could return a list or tuple to break ties when sorting too. For example, sorting first on the last element, then by the first, would look like this:

>>> sorted([[1, 1, 0], [1, 0, 1], [0, 0, 0]], key=lambda l: (l[-1], l[0]))
[[0, 0, 0], [1, 1, 0], [1, 0, 1]]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343