Home > Net >  How would you sort nested arrays in Python
How would you sort nested arrays in Python

Time:01-11

How can you sort arrays within an array in Python, ideally without an external library?

I have:

x = [[0,-1],[0,2],[7,4],[1,5],[6,3],[2,6]]

and I want to sort every x[i] so eventually I want to get:

x = [[-1,-0],[0,2],[4,7],[1,5],[3,6],[2,6]]

CodePudding user response:

Just use a comprehension and sort each sublist:

>>> [sorted(i) for i in x]
[[-1, 0], [0, 2], [4, 7], [1, 5], [3, 6], [2, 6]]

Functional programming style:

>>> list(map(sorted, x))
[[-1, 0], [0, 2], [4, 7], [1, 5], [3, 6], [2, 6]]

Note: sort is in place while sorted returns a copy

CodePudding user response:

Simply:

x = [[0,-1],[0,2],[7,4],[1,5],[6,3],[2,6]]
for obj in x:
    obj.sort()

CodePudding user response:

You might us map to apply sorted to each element following way

x = [[0,-1],[0,2],[7,4],[1,5],[6,3],[2,6]]
x = list(map(sorted,x))
print(x)

gives output

[[-1, 0], [0, 2], [4, 7], [1, 5], [3, 6], [2, 6]]
  • Related