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)]
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)]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.