1

我想附加两个列表,以便做一对明智的元素[[-1, -1], [-1, -1], [4, 2], [4, 1]]作为[[-1, -1], [-1, -1], [4, 1], [4, 2]]

可能是我将两个列表附加[4,1][4,2]一个新列表中,但a.append(list)给出了[4, 2, [4, 1]]. 我怎样才能进行成对排序或追加list[1]=[4,2]list[2]=[4,1]以便得到newlist as [[4,1],[4,2]]而不是[4, 2, [4, 1]]如何直接对它们进行成对排序而不追加,如果列表[[-1, -1], [-1, -1], [4, 2], [4, 1]][[-1, -1], [-1, -1], [4, 1], [4, 2]]

4

3 回答 3

1

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]]
于 2017-07-28T19:25:20.150 回答
0

如果您愿意使用pandas,您可以将数组导入 pandas DataFrame,然后按元素排序。这是一个例子:

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)
于 2017-07-28T19:24:56.917 回答
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)]
于 2017-07-28T19:25:10.897 回答