user124123
user124123

Reputation: 1683

Sort a list of lists containing integers

I've got a list of lists containing integers sorted at the moment by the sum of the contents:

[[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 2], [0, 1, 1], [0, 2, 0], [1, 0, 1], [1, 1, 0], [2, 0, 0], [0, 0, 3], [0, 1, 2], [0, 2, 1], [0, 3, 0], [1, 0, 2], [1, 1, 1], [1, 2, 0], [2, 0, 1], [2, 1, 0], [3, 0, 0], [0, 0, 4], [0, 1, 3], [0, 2, 2], [0, 3, 1], [0, 4, 0], [1, 0, 3], [1, 1, 2], [1, 2, 1], [1, 3, 0], [2, 0, 2], [2, 1, 1], [2, 2, 0], [3, 0, 1], [3, 1, 0], [4, 0, 0]]

I would like to sort them in ascending order by the common structure of its contents i.e like

[[1, 0, 0], [2, 0, 0], [3, 0, 0], [4, 0, 0], [0, 1, 0], [0, 2, 0], [0, 3, 0], [0, 4, 0], [0, 0, 1], [0, 0, 2], [0,0,3], [0,0,4]... ]

I have seen the docs but I can't figure out how I can do this.

Upvotes: 2

Views: 205

Answers (3)

Aya
Aya

Reputation: 41950

Is this what you're after...

>>> l = [[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 2], [0, 1, 1], [0, 2, 0], [1, 0, 1], [1, 1, 0], [2, 0, 0], [0, 0, 3], [0, 1, 2], [0, 2, 1], [0, 3, 0], [1, 0, 2], [1, 1, 1], [1, 2, 0], [2, 0, 1], [2, 1, 0], [3, 0, 0], [0, 0, 4], [0, 1, 3], [0, 2, 2], [0, 3, 1], [0, 4, 0], [1, 0, 3], [1, 1, 2], [1, 2, 1], [1, 3, 0], [2, 0, 2], [2, 1, 1], [2, 2, 0], [3, 0, 1], [3, 1, 0], [4, 0, 0]]
>>> l.sort(key=lambda x: (-x.count(0), x[::-1]))
>>> l
[[1, 0, 0], [2, 0, 0], [3, 0, 0], [4, 0, 0], [0, 1, 0], [0, 2, 0], [0, 3, 0], [0, 4, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3], [0, 0, 4], [1, 1, 0], [2, 1, 0], [3, 1, 0], [1, 2, 0], [2, 2, 0], [1, 3, 0], [1, 0, 1], [2, 0, 1], [3, 0, 1], [0, 1, 1], [0, 2, 1], [0, 3, 1], [1, 0, 2], [2, 0, 2], [0, 1, 2], [0, 2, 2], [1, 0, 3], [0, 1, 3], [1, 1, 1], [2, 1, 1], [1, 2, 1], [1, 1, 2]]

Upvotes: 5

DhruvPathak
DhruvPathak

Reputation: 43235

Use your sorting criteria function as key in the sorting.

input_list = [[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 2], [0, 1, 1], [0, 2, 0], [1, 0, 1], [1, 1, 0], [2, 0, 0], [0, 0, 3], [0, 1, 2], [0, 2, 1], [0, 3, 0], [1, 0, 2], [1, 1, 1], [1, 2, 0], [2, 0, 1], [2, 1, 0], [3, 0, 0], [0, 0, 4], [0, 1, 3], [0, 2, 2], [0, 3, 1], [0, 4, 0], [1, 0, 3], [1, 1, 2], [1, 2, 1], [1, 3, 0], [2, 0, 2], [2, 1, 1], [2, 2, 0], [3, 0, 1], [3, 1, 0], [4, 0, 0]]

sorted_list = sorted(input_list,key=my_sorting_func)

Upvotes: 1

Peter Alfvin
Peter Alfvin

Reputation: 29389

See http://docs.python.org/2/howto/sorting.html for an explanation of the Python sort capability, including a discussion of "Key Functions" which gives you whatever additional flexibility you need beyond the basic sort.

Upvotes: 1

Related Questions