2013-10-06 125 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

相關問題