Finding the index of the value which is the min or max in Python

前端 未结 8 720
深忆病人
深忆病人 2020-12-30 21:26

I\'ve got a structure of the form:

>>> items
[([[0, 1], [2, 20]], \'zz\', \'\'), ([[1, 3], [5, 29], [50, 500]], \'a\', \'b\')]

The

8条回答
  •  忘掉有多难
    2020-12-30 22:21

    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
    

提交回复
热议问题