简体   繁体   English

Python:如何找到列表中第二大的数字?

[英]Python: How to find the second highest number in a list?

def second_highest(list):
""" (list of int) -> int

How do you find the second highest value from the list of integers without using remove, pop, or sort (which I tried) since I need to use the same list later on?你如何在不使用删除、弹出或排序(我尝试过)的情况下从整数列表中找到第二大值,因为我稍后需要使用相同的列表?

There will be no duplication of numbers.不会有重复的数字。

list.sort()
return list[-2]

I tried removing the highest number using max, sorting the list, but since those mutates the list, I can't use them.我尝试使用 max 删除最高数字,对列表进行排序,但由于这些改变了列表,我无法使用它们。

Use the builtin sorted oy mylist , which will not modify mylist (thanks to @Tofystedeth)使用内置sorted oy mylist ,它不会修改mylist (感谢@Tofystedeth)

mylist = [1, 2, 8, 3, 12]
print(sorted(mylist, reverse=True)[1])
data = [1,2,8,3,12]

largest = None
second_largest = None

for a in data:
    if not largest or a > largest:
        if largest:
            second_largest = largest
        largest = a

print("largest: {}".format(largest))
print("second_largest: {}".format(second_largest))
 arr = [2, 3, 4, 2, 4, -3, 43, -4, -25, 45, 9]
 my_list = list(set(arr))
 my_list.sort()
 if len(my_list) == 1:
     print(my_list[0])
 elif len(my_list) >= 2:
     print(my_list[-2])
nums=[1,2,3,3,5,4,5,5,2]

#making new set to maintain uniqueness
new_list= set(nums)

high= max(nums)
new_list.remove(high)
print(max(new_list))

#This code uses remove but does not do any changes to the given list
print(nums)
array = [2, 3, 4, 2, 4, -3, 43, -4, -25, 45, 9]

arr = array.copy()

z = max(arr)

# if list contains duplicate max elements removing them until We get Second highest

while max(arr) == z:
  arr.remove(max(arr))

print(max(arr))
print(array)

Here is the code to find the 2nd largest number in the list without using any inbuilt functions.这是在不使用任何内置函数的情况下查找列表中第二大数字的代码。

data = [11,22,1,2,5,67,21,32]

max1 = data[0] # largest num
max2 = data[1] # second largest num


for num in data:
    if num > max1:
        max2 = max1 # Now this number would be second largest
        max1 = num # This num is largest number in list now.
    
    # Check with second largest
    elif num > max2:
        max2 = num # Now this would be second largest.

print(max2)

I think my answer is more simple and more readable for beginners我认为我的答案对初学者来说更简单,更易读

x=[2,3,4,2,5,9,8,4,5,6,7,8,9,2,1,3,4,5]

max=-10000000
for i in x:
    if(i>max):
        secondmax=max
        max=i
    elif(i>secondmax and i!=max):
        secondmax=i
    
        
print(secondmax)   
    

##This will work even if numbers are negative. ##即使数字为负数,这也会起作用。 Logic is : convert the list() to set() and back to list to use the sort() method and then print the -2 position value in the list.逻辑是:将 list() 转换为 set() 并返回到 list 以使用 sort() 方法,然后打印列表中的 -2 位置值。 This gives you the second-highest value.## "Python 3"这为您提供了第二高的价值。## "Python 3"

if __name__ == '__main__':
    n = int(input())
    arr = list(map(int, input().split()))
    z = list(set(arr))
    z.sort()
    print(z[-2])

Here is a way to do it using sort.这是一种使用排序的方法。 However, it gives you the possibility to reuse the list since you are temporarily storing the list arr in sortedArr .但是,它使您有可能重用列表,因为您暂时将列表arr存储在sortedArr中。 Calling arr by itself would return the original list.单独调用arr将返回原始列表。 Here you can Try it online!在这里您可以在线试用!

# Finding a runner up number in a List of Arrays
# Second highest number in a list

arr = [2,3,6,6,5]
sortedArr = sorted(arr,reverse=True)    # Sorting the array in descending order.
highest = sortedArr[0]  # Assign the highest value in the array to the variable `highest`.
secondHighest = 0   # Initializing the variable `secondHighest` to 0.


for x in (sortedArr):   # Iterating through the sorted array and checking if the value is equal to the highest value. 
    if(x == highest):
        continue    # If it is, it will continue to the next value. 
    else:
        secondHighest = x   # If it is not, it will assign the value to the variable `secondHighest` 
        break   # break out of the loop.

print(secondHighest)    # Printing the value of the variable `secondHighest`.

>>> 5
list = [2,3,5,1,7,8]
secondhighest = max([i for i in list if i<max(a)])

This will give you the second highest value in the list.这将为您提供列表中第二高的值。

  1. Copy unique list elements to another list (if Already the list elements are unique, go to step 2) .将唯一列表元素复制到另一个列表(如果列表元素已经是唯一的,请转到步骤 2)。

  2. You should find the maximum in the list and save its index.您应该在列表中找到最大值并保存其索引。 Then remove it from the list using the remove() function and then find the maximum of the new list (with the original maximum value removed) and that will be your second highest element.然后使用remove()函数将其从列表中remove() ,然后找到新列表的最大值(删除原始最大值),这将是您的第二大元素。 You can then use the insert() method to add back the original maximum back into the list.然后,您可以使用insert()方法将原始最大值重新添加到列表中。

Here is the code to find the maximum and second maximum number in a list or array(python).这是在列表或数组(python)中查找最大和第二个最大数字的代码。 Tried with all the combination of elements(negative and positive), it is working fine.尝试了所有元素的组合(负面和正面),它工作正常。 We can optimize this code as i am not using any inbuilt method.我们可以优化此代码,因为我没有使用任何内置方法。 Below is the list combinations this code is tested with: la = [1,1,1,1,1],la = [1,1,1,1,1,0],la = [5,4,1,2,3],la = [3,6,2,7],la = [1,2,3,4,5],la = [4,5,1,2,3],la = [5,5,4,3,2,1],la = [-1,1,0,0,0],la = [-1,-2,-3,-4], la = [-1,0],la = [-2,-2,-2,-2,0,1,1,1,1]以下是此代码测试的列表组合:la = [1,1,1,1,1],la = [1,1,1,1,1,0],la = [5,4,1, 2,3],la = [3,6,2,7],la = [1,2,3,4,5],la = [4,5,1,2,3],la = [5, 5,4,3,2,1],la = [-1,1,0,0,0],la = [-1,-2,-3,-4], la = [-1,0] ,la = [-2,-2,-2,-2,0,1,1,1,1]

def findSecmax(la):
    mx = la[0]
    sec = 0 # or sec = min(la) or we can take (- sys.maxsize)
    for i in la:
        if i < sec:
            sec = i

    for i in la:
        if i > mx:
            mx = i

    for i in la:
        if i > sec and mx > i:
            sec = i

    if sec == mx:
        return  "we have same elements in the list. So max is {}".format(mx)
    else:
        return mx,sec


print(findSecmax(la))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM