[英]Python - Sorting a 2D array using each column
I would like to sort a 2D array with three columns in the following fashion: 我想按以下方式对具有三列的2D数组进行排序:
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.