Adam_G
Adam_G

Reputation: 7879

Return a sorted list of indices from list of lists

If I have a list of lists, I know I can get the index of the largest item using a solution posted here:

def get_maximum_votes_index(L):
    return max((n,i,j) for i, L2 in enumerate(L) for j, n in enumerate(L2))[1:]

However, if I want to return a sorted list of indices, descending from the maximum, how would I do that?

For example:

L = [[1,2],[4,3]]

Would return:

[(1,0),(1,1),(0,1),(0,0)]

Upvotes: 0

Views: 41

Answers (1)

Aran-Fey
Aran-Fey

Reputation: 43286

You basically just need to replace the max with sorted:

L = [[1,2],[4,3]]

# step 1: add indices to each list element
L_with_indices = ((n,i,j) for i, L2 in enumerate(L) for j, n in enumerate(L2))

# step 2: sort by value
sorted_L = sorted(L_with_indices, reverse=True)

# step 3: remove the value and keep the indices
result = [tup[1:] for tup in sorted_L]
# result: [(1, 0), (1, 1), (0, 1), (0, 0)]

Upvotes: 3

Related Questions