查找具有最高第二元素的列表(Python)

时间:2013-10-06 02:42:46

标签: python list element

我有一个由列表(元组?)组成的列表,它们遵循以下表格

[(2,1),(3,0),(4,3),(5,2),(9,2),(7,4)]

我需要确定满足所列标准的元素:

  1. 具有最高的第二(?)值。例如,在上面的示例中,输出将为7.
  2. 如果是tie,则第一个(?)值最低的元素。例如:

    [(5,1),(4,2),(1,2),(9,3),(8,3)]
    

    这将返回8; 9和8都具有最高的第二(?)值,所以在抢七局中,8低于9,所以8胜。

  3. *我把我的术语放错了,但希望我的帖子可读

3 个答案:

答案 0 :(得分:2)

只需按第二个然后第一个元素排序:

>>> lst=[(8,4),(2,1),(3,0),(4,3),(5,2),(9,2),(7,4)]
>>> sorted(lst, key=lambda x: (x[1], -x[0]))[-1]
(7, 4)

再想一想,您不需要对整个列表进行排序以找到一个元素。使用具有相同键功能的max

>>> lst=[(8,4),(2,1),(3,0),(4,3),(5,2),(9,2),(7,4)]
>>> max(lst, key=lambda x: (x[1], -x[0]))
(7, 4)

答案 1 :(得分:1)

实施您自己的分拣机:

>>> l=[(5,1),(4,2),(1,2),(9,3),(8,3)]
>>> def sorter(t1, t2):
...     # if the second elements are equal sort based on the first
...     if t1[1] == t2[1]:
...             # positive return means higher value
...             return t1[0] - t2[0]
...     return t2[1] - t1[1]
... 
>>> l.sort(sorter) # in place
>>> l
[(8, 3), (9, 3), (1, 2), (4, 2), (5, 1)]
>>> l[0]
(8, 3)

答案 2 :(得分:1)

您也可以通过列表一次完成此操作,而无需对其进行排序:

l = [(2,1),(3,0),(4,3),(5,2),(9,2),(7,4)]

def max_second_val(lst):

    max = lst[0]    #Take first tuple to be the max

    for tup in lst:                # As you iterate through the tuples...
        if tup[1] == max[1]:       # If the 2nd elem of the current tuple is equal
            if tup[0] < max[0]:    # to 2nd elem of curr max, and the first elem of curr
                max = tup          # tuple is smaller, take this to be the new max
        elif tup[1] > max[1]:      # Otherwise, if 2nd elem of curr tuple is bigger than
            max = tup              # curr max, take this to be the new max

    return max