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

前端 未结 8 640
深忆病人
深忆病人 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:00

    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)]
    
    0 讨论(0)
  • 2020-12-30 22:05
     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.

    0 讨论(0)
  • 2020-12-30 22:13

    Yet another way to get the argmax is:

    def argmax(lst):
        return max(range(len(lst)), key=lst.__getitem__)
    
    0 讨论(0)
  • 2020-12-30 22:15

    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]
    
    0 讨论(0)
  • 2020-12-30 22:20

    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.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题