2013-10-06 126 views
0

我有一个列表由列表(元组?),他们也跟着下面在列表中找到最高的第二个元素(Python)的

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

我需要找出满足上市条件的元素形式:

  1. 具有最高的第2(?)值。例如,在上面的示例中,输出将为7.
  2. 在关系事件中,具有最低1st(?)值的元素。例如:

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

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

*我把s其中我的术语可能是错的,但希望我的职务将是可读的

回答

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) 
+0

我用[(5,1),(4,2),(1,2),(9,3),(8,3)]代替了你的sorted()中的lst,然后返回(9, 3)它应该返回的位置(8,3) –

+1

@NoobCoder:在此工作:http://ideone.com/oF1Vbq – georg

+0

在codecademy实验室编辑器中再次尝试,我一定在某个地方犯了错误。只是让我明白你在做什么,key = lambda:(x [1],-x [0]))[ - 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) 
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 
+0

好主意,虽然在Python中它是'max(key = ...)'。 – georg

相关问题