1

i want to append two list as in order to do a pair wise sort of elements [[-1, -1], [-1, -1], [4, 2], [4, 1]] to make as [[-1, -1], [-1, -1], [4, 1], [4, 2]]

it may be that i append two list [4,1] and [4,2] into a new list but a.append(list) gives [4, 2, [4, 1]] . how can i do a pair wise sort or append list[1]=[4,2] and list[2]=[4,1] as in order to get newlist as [[4,1],[4,2]] instead of [4, 2, [4, 1]] also how to do pair wise sort on them directly without appending if the list is as [[-1, -1], [-1, -1], [4, 2], [4, 1]] to [[-1, -1], [-1, -1], [4, 1], [4, 2]]

imshashi17
  • 177
  • 1
  • 3
  • 12

3 Answers3

2

What you want is a list of lists, so try this:

In [1]: list1 = []

In [2]: list1.append([1,2])

In [3]: list1.append([3,4])

In [4]: list1.append([3,2])

In [5]: list1
Out[5]: [[1, 2], [3, 4], [3, 2]]

And sorted:

In [6]: sorted(list1)
Out[6]: [[1, 2], [3, 2], [3, 4]]
Johannes
  • 3,300
  • 2
  • 20
  • 35
  • In addition to @Johannes answer: There is a `reverse` argument for [`sorted`](https://wiki.python.org/moin/HowTo/Sorting) which is quite handy if output needs to be in opposite order: `sorted(list1, reverse=True)` – albert Jul 28 '17 at 19:29
0

If you are open to using pandas, you can import your array into a pandas DataFrame, and then sort by elements. Here's an example:

import pandas as pd
df = pd.DataFrame([[-1, -1], [-1, -1], [4, 2], [4, 1]])
df.sort([0,1],inplace=True)
print(df.values)
array([[-1, -1],
       [-1, -1],
       [ 4,  1],
       [ 4,  2]], dtype=int64)
nanojohn
  • 572
  • 1
  • 3
  • 13
0

From your example, it's not clear if the pairs are sorted together or separately

Sort pairs together

>>> matrix = [[-1, -1], [-1, -1], [4, 2], [4, 1]]
>>> sorted(matrix)
[[-1, -1], [-1, -1], [4, 1], [4, 2]]

Sort pairs separately

You can use zip to transpose your matrix, sorted to sort the rows and zip to transpose your sorted rows back into the matrix:

>>> zip(*matrix)
[(-1, -1, 4, 4), (-1, -1, 2, 1)]
>>> [sorted(row) for row in zip(*matrix)]
[[-1, -1, 4, 4], [-1, -1, 1, 2]]
>>> zip(*[sorted(row) for row in zip(*matrix)])
[(-1, -1), (-1, -1), (4, 1), (4, 2)]

With another matrix as input, the difference becomes clearer:

>>> matrix = [[1, 2], [3, 1], [2, 3]]
>>> sorted(matrix)
[[1, 2], [2, 3], [3, 1]]
>>> zip(*[sorted(row) for row in zip(*matrix)])
[(1, 1), (2, 2), (3, 3)]
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
  • final output is list of tuples instead of list of list, not sure if it matters, but just wanted to point out – nanojohn Jul 28 '17 at 19:28
  • @nanojohn: Thanks. More important would be to know how the sorting should be applied. The input data doesn't make it clear. – Eric Duminil Jul 28 '17 at 19:29