简体   繁体   中英

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.

Use the builtin sorted oy mylist , which will not modify mylist (thanks to @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. This gives you the second-highest value.## "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 . Calling arr by itself would return the original list. 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. 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. You can then use the insert() method to add back the original maximum back into the list.

Here is the code to find the maximum and second maximum number in a list or array(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]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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