-1

I need to sort an array of arrays by a specific element

This is an array:

arr= 
[0, [71, 554, 258, 793]]
[1, [61, 415, 148, 593]]
[2, [91, 145, 658, 893]]

I need to be able to sort it by arr[0][0] as well as by any element from the internal array like arr[0][1] or arr[0][2]

currently, I'm able to sort it by using key=itemgetter(1) where: itemgetter(1) - is second element of array [0, [71, 554, 258, 793]] in this cese = 71

from operator import itemgetter
array = sorted(array, key=itemgetter(1))
print(*array[:], sep="\n")

how to sort this array by any element from the internal array [71, 554, 258, 793]?

so if I'm sorting by the second element from internal array output should be like this: (column 145, 415, 554)

arr= 
[2, [91, 145, 658, 893]]
[1, [61, 415, 148, 593]]
[0, [71, 554, 258, 793]]

if I'm sorting by the third element from internal array output should be like this: (column 148, 258, 658)

arr= 
[1, [61, 415, 148, 593]]
[0, [71, 554, 258, 793]]
[2, [91, 145, 658, 893]]

this is kinda similar to this question: Python Sort Multidimensional Array Based on 2nd Element of Subarray

5
  • 2
    sorted(arr, key=lambda x: x[1][1]) Commented May 30, 2019 at 22:56
  • How are you stuck with this? You simply replace that 1 constant with a variable that contains the column number. Commented May 30, 2019 at 23:00
  • @Prune I wish it would be so straight forward but it's not, u see that index 1 is related to the second element of the first array [A, [B, C, D]] where element 0 = A element 1 is [B, C, D] and there's no element 2 it should be like calling the array element arr[0][2] but this syntax doesn't work in this context with key=itemgetter(1)) Commented May 30, 2019 at 23:28
  • @Will Thanks man that's what I need!! Commented May 30, 2019 at 23:31
  • @NickPV feel free to mark the answer you need as "accepted" Commented May 31, 2019 at 7:00

1 Answer 1

1

Just define a function that decides on the key to use. You can use a partial function to create this function based on the key index

from functools import partial

def sort_key(si, x):
    return x[1][si]

sort_index = 1  # or 1 or 2

partial_sort_key = partial(sort_key, sort_index)

print(sorted(arr, key=partial_sort_key))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.