0

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

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

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

  1. 具有最高的 2nd(?) 值。例如,在上面的示例中,输出将为 7。
  2. 在平局的情况下,具有最低 1st(?) 值的元素。例如:

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

    这将返回 8;9 和 8 都具有最高的 2nd(?) 值,因此在抢七局中,8 低于 9,因此 8 胜。

*我把 ?s 放在我的术语可能有误的地方,但希望我的帖子可以阅读

4

3 回答 3

2

只需按第二个然后 -first 元素对其进行排序:

>>> 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)
于 2013-10-06T02:47:27.107 回答
1

Implement your own sorter:

>>> 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)
于 2013-10-06T02:48:39.487 回答
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
于 2013-10-06T05:46:16.463 回答