user2918984
user2918984

Reputation: 121

sorting nested tuple list

So, what I am trying to do, is to sort a list with that contains (num, tuple) I want to sort it first by the second value of the tuple and if 2 are equal, I want to sort it by the num(of the first tuple).

So lets say I have:

l = [(1,(2,3)),(3,(2,1)),(2,(2,1))]
print(l.sort(key=something))
[(2,(2,1)), (3,(2,1)), (1,(2,3))]

I have tried:

l.sort(key=itemgetter(1,0)

Of course it didn't work. Any ideas?

Thank you.

Upvotes: 2

Views: 1932

Answers (3)

user2555451
user2555451

Reputation:

operator.itemgetter works fine:

>>> from operator import itemgetter
>>> l = [(1,(2,3)),(3,(2,1)),(2,(2,1))]
>>> l.sort(key=itemgetter(1,0))
>>> print(l)
[(2, (2, 1)), (3, (2, 1)), (1, (2, 3))]
>>>

I think the problem is that you tried to print the result of list.sort. You cannot do this because it is an in-place method (it always returns None).

Upvotes: 4

MB-F
MB-F

Reputation: 23637

this works too:

l.sort(key=lambda x: x[::-1])

Note that list.sort sorts the list in place, so print(l.sort(key=something)) would print None.

Upvotes: 0

dawg
dawg

Reputation: 103844

>>> l = [(1,(2,3)),(3,(2,1)),(2,(2,1))]
>>> sorted(l, key=lambda t: (t[1][1],t[0]))
[(2, (2, 1)), (3, (2, 1)), (1, (2, 3))]

Or:

>>> from operator import itemgetter
>>> sorted(l, key=itemgetter(1,0))
[(2, (2, 1)), (3, (2, 1)), (1, (2, 3))]

Upvotes: 0

Related Questions