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

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

    so this is a real quick and easy way to get that efficient version you are looking for:

    a = []
    count = 0
    for i in items:
        for x in i[0]:
            #place a list with the index next to it in list a for sorting
            a.append((x,count))
    #continually grabs the smallest list and returns the index it was in
    sort = [a.pop(a.index(min(a)))[1] for i in range(len(a))]
    

    Here is it with your items to show that it works:

    >>> items = [([[0, 1], [2, 20]], 'zz', ''), ([[1, 3], [5, 29], [50, 500]], 'a', 'b')]
    >>> a = []
    >>> count = 0
    >>> for i in items:
    ...     for x in i[0]:
    ...             a.append((x,count))
    ...     count += 1
    ... 
    >>> sort = [a.pop(a.index(min(a)))[1] for i in range(len(a))]
    >>> sort
    [0, 1, 0, 1, 1]
    

提交回复
热议问题