1

I have a list called V. The elements of V will be one of be one of: 0,1,2 or +inf

I would like to sort this list such that 2 is always at the beginning and the list is sorted in ascending order from then on.

For example, if the list is initially V = [0,1,2,inf] It should then become V = [2,0,1,inf]

I have a good idea of how to do this with conditionals and appending into a new list, but if possible I'd like to sort this with a key or a comprehension.

I am writing this in Python3 but I would prefer to not import anything

1 Answer 1

2

Use a lambda to create a tuple and test if the first element is one of the preferred values:

>>> V = [0,1,2,float('inf')] 
>>> sorted(V, key=lambda e: (e!=2, e))
[2, 0, 1, inf]

So the tuple will be one of (True, the_value) or (False, the_value). False < True and that trumps whatever the second actual value in the tuple is.

If you have more than one preferred value, you can use in with a tuple of preferred values:

>>> sorted(V, key=lambda e: (e not in (1,2), e))
[1, 2, 0, inf]
>>> sorted(V, key=lambda e: (e not in (2,0), e))
[0, 2, 1, inf]

You could also create a comprehension:

>>> [(e not in (0,2),e) for e in V]
[(False, 0), (True, 1), (False, 2), (True, inf)]

And then sort that:

>>> [t[1] for t in sorted((e not in (0,2),e) for e in V)]
[0, 2, 1, inf]

Which is a form of Decorate, Sort, Undecorate

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

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.