2

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.

1
  • I get exactly the result you say you want with itemgetter Commented Jan 4, 2014 at 17:07

3 Answers 3

4

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).

Sign up to request clarification or add additional context in comments.

Comments

0
>>> 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))]

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.