简体   繁体   中英

How to sort 2D list elements in python?

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

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]]
for item in a:
    item.sort()

You could try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM