【问题标题】:Find second maximum number in a list [duplicate]在列表中查找第二个最大数
【发布时间】:2015-08-03 15:06:43
【问题描述】:

第一行包含 N。第二行包含 N 个整数的列表,每个整数用空格分隔。我需要找到列表中第二大的数字。

我的代码:

N = int(raw_input())
L = map(int, raw_input().split())

for i in L:
    if i == max(L):
        L.remove(i)
print L
print max(L)

如果输入是 [2, 6, 9, 9, 5],这仍然会打印最大值:9,因为只有一个 9 从列表中删除。

那么,如何删除列表中的所有第一个最大值?

谢谢

【问题讨论】:

  • this 的可能细微变化。

标签: python


【解决方案1】:

它仍然返回 9 的原因是因为您在迭代列表时正在改变它。基本上这些步骤是:

1.    2  6  9  9  5
      ^idx0
2.    2  6  9  9  5
         ^idx1
3.    2  6  9  9  5
            ^idx2
  3a. 2  6  9  5
            ^idx2
4.    2  6  9  5
               ^

看看它是如何在删除前 9 时跳过评估第二个 9 的?您会注意到,如果您的列表是 [2, 6, 9, 5, 9],它可以正常工作。

要使其正常运行,对代码进行的最小更改是迭代列表的副本,而不是列表本身。

L = [2, 6, 9, 9, 5]

maxL = max(L)  # gotta move this out!!
for i in L[:]:  # the slice creates a copy
    if i == maxL:
        L.remove(i)

print(max(L))

但是,创建一个集合(确保唯一性)、对其进行排序并返回倒数第二个条目可能更容易。

second_max = sorted(set(L))[-2]

【讨论】:

    【解决方案2】:

    试试

    N = 5
    L = map(int, "2 6 9 9 5".split())
    
    maxL = max(L)
    #list comprehension for remove all occurrences of max(L)
    L_filter = [e for e in L if e!=maxL]
    print L
    #print max of L_filter, second maximum of L
    print max(L_filter)
    

    你得到:

    [2, 6, 9, 9, 5]
    6
    

    【讨论】:

      【解决方案3】:

      通过转换为集合来删除重复的元素:

      values = set(L)
      

      然后去掉最大值:

      values.discard(max(values))
      

      【讨论】:

      • 好像如果你打算做两次max(values),你还不如只做sorted(set(L))[-2]
      • @Adam 我就是这样做的,因为它更简单,但有人可能会争辩说排序是 O(n log n),而计算最大值仍然是 O(n)。
      【解决方案4】:

      你也可以这样做

      L = [2, 6, 9, 9, 5]
      L_tuples = zip(L, range(len(L))) #need tuples to make a dict
      L_map = dict(L_tuples)           #use the dict to dedupe
      L_uniq = L_map.keys()            #get back deduped values
      L_sorted = sorted(L_uniq)        #sort them ascending
      second_largest = L_sorted[-2]    #second from last is second largest
      
      #or, rolling all that up...
      second_largest = sorted(dict(zip(L, range(len(L)))).keys())[-2]
      

      【讨论】:

      • 当然,您也可以使用set 而不必创建dict。只是展示了在 python 中进行重复数据删除的其他方法
      【解决方案5】:
      >>> import heapq
      >>> values = [2, 6, 9, 9, 5]
      >>> heapq.heapify(values)
      >>> heapq._heapify_max(values)
      >>> value = top = heapq.heappop()
      >>> while value == top:
      ...     value = heapq.heappop()
      >>> print value
      

      【讨论】:

        【解决方案6】:

        这是计算列表中第二个最大值的另一种方法。该代码还考虑了列表中包含重复元素的场景。

        number_of_elements=int(input('The number of elements in list\n'))
        
        a=[]
        for i in range(number_of_elements):
            a.append(int(input('enter the list elements')))
        
        
        #Use built-in function to calculate the maximum
        
        max_list=max(a)
        
        print("The maximum element is ",max_list)
        
        #Calculate the number of times the number occur
        
        count_of_max_num=a.count(max_list)
        
        b=a
        
        if (count_of_max_num == 1):
        
            b.remove(max_list)
            second_max=max(b)
            print("The second largest number is", second_max, "The new list is" ,b)
        else:
            for i in range(count_of_max_num):
                b.remove(max_list)
            print ("The second largest is" , max(b))
        

        【讨论】:

          猜你喜欢
          • 2011-06-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-02-01
          • 1970-01-01
          • 1970-01-01
          • 2014-02-26
          相关资源
          最近更新 更多