简体   繁体   English

Python-使用每列对2D数组排序

[英]Python - Sorting a 2D array using each column

I would like to sort a 2D array with three columns in the following fashion: 我想按以下方式对具有三列的2D数组进行排序:

  • First, the array goes through the one of the columns and sorts each number based on the value. 首先,该数组通过其中一列,并根据该值对每个数字进行排序。
  • Then, if there are any "ties", the program uses another column to sort out the ties. 然后,如果有任何“关系”,程序将使用另一列来整理关系。
  • Finally, it uses the remaining column to sort out any ties still existing. 最后,它使用剩余的列来整理仍然存在的任何联系。

Example: 例:

[[6, 0, "Hello"],
 [4, 1, "Jane"],
 [3, 0, "Text"],
 [4, 1, "Bob"]]

The columns in order of importance are: 1, 0, 2. This means we check the 2nd column, then the first, and finally the last. 按重要性顺序排列的列是:1、0、2。这意味着我们先检查第二列,然后是第一列,最后是最后一列。

[[6, 0, "Hello"],
 [3, 0, "Text"],
 [4, 1, "Jane"],
 [4, 1, "Bob"]]

Now, we use the first column: 现在,我们使用第一列:

[[3, 0, "Text"],
 [6, 0, "Hello"],
 [4, 1, "Jane"],
 [4, 1, "Bob"]]

Finally, we use the last column: 最后,我们使用最后一列:

[[3, 0, "Text"],
 [6, 0, "Hello"],
 [4, 1, "Bob"],
 [4, 1, "Jane"]]

It is not hard to just sort it based on one column and disregard any duplicates. 不难根据一列对其进行排序而忽略任何重复项。 That is shown here: Sorting a 2D array using the second column C++ . 如此处所示: 使用第二列C ++对2D数组进行排序 I tried data.sort(key=itemgetter(1)) , but it only worked for one column. 我尝试了data.sort(key=itemgetter(1)) ,但它仅适用于一列。

I have no idea how to proceed with this. 我不知道该如何进行。 Please help! 请帮忙!

from operator import itemgetter

data = [[6, 0, "Hello"],
        [4, 1, "Jane"],
        [3, 0, "Text"],
        [4, 1, "Bob"]]

data.sort(key=itemgetter(1, 0, 2))

print(data)  # [[3, 0, 'Text'], [6, 0, 'Hello'], [4, 1, 'Bob'], [4, 1, 'Jane']]

To help understand: 为了帮助理解:

key_function = itemgetter(1, 0, 2)
print(key_function([6, 0, "Hello"]))  # (0, 6, 'Hello')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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