0

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

  • 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.

[[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!

1 Answer 1

1
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')
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I tried data.sort(key=itemgetter(1, 0, 2)) but I didn't know that it could take more than one parameter.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.