Nairit
Nairit

Reputation: 163

Python - Sorting a 2D array using each column

I would like to sort a 2D array with three columns in the following fashion:

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.

[[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++. I tried data.sort(key=itemgetter(1)), but it only worked for one column.

I have no idea how to proceed with this. Please help!

Upvotes: 0

Views: 154

Answers (1)

Alex Hall
Alex Hall

Reputation: 36033

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')

Upvotes: 1

Related Questions