1

I need to know how to sort the list elements in python without changing their position.

    a = [[5, 4, 5], [4, 5, 6], [2, 8, 2], [5, 2, 2]]
    b = [[3, 2, 4], [3, 6, 7], [3, 6, 0], [7, 2, 1]]
    c = [[x + y for x, y in zip(s1, s2)] for s1, s2 in zip(a, b)]
    c.sort(key=lambda x: x[1])
    c.reverse()
    for c in c:
        print(c)

I tried using the lambda but it sorts them by the first number, thus changing the order. I need to sort array c so it would look something like this:

Input: c = [[5, 4, 5], [4, 5, 6], [2, 8, 2], [5, 2, 2]]
Output: c = [[4, 5, 5], [4, 5, 6], [2, 2, 8], [2, 2, 5]]

I hope i made myself clear enough, any help is appreciated

3 Answers 3

3

You can do this in your original list comprehension using sorted on the inner list comprehension.

>>> [sorted(i+j for i, j in zip(s1, s2)) for s1, s2 in zip(a, b)]
[[6, 8, 9], [7, 11, 13], [2, 5, 14], [3, 4, 12]]
Sign up to request clarification or add additional context in comments.

Comments

2
for item in a:
    item.sort()

Comments

2

You could try this:

c = [sorted(x) for x in a]

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.