I\'ve got a structure of the form:
>>> items
[([[0, 1], [2, 20]], \'zz\', \'\'), ([[1, 3], [5, 29], [50, 500]], \'a\', \'b\')]
The
This works:
by_index = ([sub_index, list_index] for list_index, list_item in
enumerate(items) for sub_index in list_item[0])
[item[1] for item in sorted(by_index)]
Gives:
[0, 1, 0, 1, 1]
In detail. The generator:
by_index = ([sub_index, list_index] for list_index, list_item in
enumerate(items) for sub_index in list_item[0])
list(by_index)
[[[0, 1], 0], [[2, 20], 0], [[1, 3], 1], [[5, 29], 1], [[50, 500], 1]]
So the only thing needed is sorting and getting only the desired index:
[item[1] for item in sorted(by_index)]
from operator import itemgetter
index, element = max(enumerate(items), key=itemgetter(1))
Return the index of the biggest element in items
and the element itself.
Yet another way to get the argmax is:
def argmax(lst):
return max(range(len(lst)), key=lst.__getitem__)
This method finds the index of the maximum element of any iterable and does not require any external imports:
def argmax(iterable):
return max(enumerate(iterable), key=lambda x: x[1])[0]
The index of the max of a list:
def argmax(lst):
return lst.index(max(lst))
If there are duplicate max values in lst, this will return the index of the first maximum value found.
It's easy if you don't try to use the fact that the internal range lists are sorted
sorted(sum([ [(rng,) + i[1:] for rng in i[0]] for i in items ], []), lambda i: i[0][0])
It sounds like you want a function that returns the index of the smallest value though
def min_idx(l, key=lambda x: x):
min_i, min_key = None, float('inf')
for i, v in enumerate(l):
key_v = key(v)
if key_v < min_key:
mini_i = i
min_key = key_v
return min_i
def merge_items(items):
res = []
while True:
i = min_idx(items, key=lambda i: i[0][0][0])
item = items[i]
res.append((item[0][0],) + item[1:])
return res