+ 2

How can I sort a list and print the second largest element in it using python 3?

List sorting in python I'm getting a Nonetype error

6th Apr 2020, 5:05 AM
Ashutosh Thite
Ashutosh Thite - avatar
6 Respostas
+ 3
you can do it in a way like this: x=[3,7,8,6] x.remove(max(x)) print(max(x)) #output is 7
6th Apr 2020, 5:12 AM
Tricker
+ 2
If your list is sorted, you don't have to iterate over all element to find the nth-max... if increasing order mx2 = list[-2] if decreasing order mx2 = list[1] ... until you've only uniques elements in the list. If values can be repeated in the list, you need to iterate only over a list subpart: def mx2(list,inc=True): i = len(list)-1 if inc else 0 inc = -1 if inc else 1 M = list[i] try: while list[i]==M: i += inc except Exception: return None return list[i]
6th Apr 2020, 6:49 AM
visph
visph - avatar
+ 1
x = list(set([1, 4, 2, 4, 6])) print(x[-2]) hehe
6th Apr 2020, 11:14 AM
Francis Sullano
Francis Sullano - avatar
0
>>> a = [1,2,4,5,6,72,1,3] >>> sorted(a)[-2:-1]#start 2 position from left, stop in position from end [6]#returns array >>> sorted(a)[-2:-1][0]#pick first element 6 >>>
6th Apr 2020, 8:53 AM
v0ltr0n
0
v0ltr0n no needs to slice before accessing the targeted value... Francis Sullano using a set imply implicitly to iterate over the whole list (wich could be time expensive for large list and/or numerous call) ;)
6th Apr 2020, 11:18 AM
visph
visph - avatar
0
mylist = [1, 1, 2, 2, 3, 3, 10, 10, 4, 4, 8, 8, 6, 6, 7, 7, 5, 5, 9, 9] print(sorted(set(mylist))[-2])
6th Apr 2020, 5:36 PM
rodwynnejones
rodwynnejones - avatar