如何在python中对2D列表元素进行排序?

时间:2020-05-26 11:18:24

标签: python arrays sorting

我需要知道如何在python中对列表元素进行排序而不更改其位置。

    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)

我尝试使用lambda,但它会按第一个数字对它们进行排序,从而更改了顺序。 我需要对数组c进行排序,使其看起来像这样:

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

我希望我已经说清楚了,感谢您的帮助

3 个答案:

答案 0 :(得分:3)

您可以使用内部列表理解中的sorted在原始列表理解中进行此操作。

>>> [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]]

答案 1 :(得分:2)

for item in a:
    item.sort()

答案 2 :(得分:2)

您可以尝试以下方法:

c = [sorted(x) for x in a]
相关问题