简体   繁体   中英

Find sublist of second largest elements in a list (Python 3)

Given a list:

lis = [37.21, 37.21, 37.2, 44, 44, 44, 101, 101]

What is a simple way to extract the second-largest elements?

 [44, 44, 44]

My attempt

lis = [37.21, 37.21, 37.2, 44, 44, 44, 101, 101]
def sublist_of_second_largest(lis):
    maxx=max(lis)
    n=lis.count(maxx)
    for i in range(n):
        lis.remove(maxx)
    maxx=max(lis)
    n=lis.count(maxx)
    out=[]
    for i in range(n):
        out.append(maxx)
    return out

print(sublist_of_second_largest(lis))

Simple pythonic way:

lis = [37.21, 37.21, 37.2, 44, 44, 44, 101, 101]
num = sorted(set(lis), reverse=True)[1]
print([i for i in lis if i == num])

Ouput:

[44, 44, 44]

While Zain's answer is correct and consice, due to the sorting it has an O(n log n) runtime. This might not matter to you, but if it does here is an O(n) implementation:

def sublist_of_second_largest(num_lst):
    num_set = set(num_lst)
    num_set.remove(max(num_set))
    snd_largest_num = max(num_set)
    return [val for val in num_lst if val == snd_largest_num]

print(sublist_of_second_largest([37.21, 37.21, 37.2, 44, 44, 44, 101, 101]))

Prints:

[44, 44, 44]

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