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

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

给定一个列表:

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

提取第二大元素的简单方法是什么?

[44, 44, 44]

我的尝试

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

简单的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])

输出:

[44, 44, 44]

虽然 是正确且简洁的,但由于排序,它的运行时间为 O(n log n)。这对您来说可能无关紧要,但如果确实如此,这是一个 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]))

打印:

[44, 44, 44]