简体   繁体   English

查找列表中第二大元素的子列表(Python 3)

[英]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:简单的pythonic方式:

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] [44, 44, 44]

While Zain's answer is correct and consice, due to the sorting it has an O(n log n) runtime.虽然Zain 的答案是正确且简洁的,但由于排序,它具有 O(n log n) 运行时间。 This might not matter to you, but if it does here is an O(n) implementation:这对你来说可能无关紧要,但如果它在这里是一个 O(n) 实现:

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]

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

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