繁体   English   中英

Python 列表中第四大元素的程序?

[英]Python program for fourth largest element in the list?

我已经编写了代码,但它显示的第四大元素不正确 output。让我知道我该怎么办?

test=[4, 6, 9, 4, 3, 88, 3, 2]
test.sort()
print("Original list: ",test)
res=[]
for i in test:
    if i not in res:
             res.append(i)
print("Removing duplicates: ",res)
print("4th largest element: ",test[-4])

你非常接近你可以只使用排序 function 中的构建并获得返回值的 [-4] 索引

test = [4, 6, 9, 4, 3, 88, 3, 2]
fourth = sorted(test)[-4]
print(fourth)

要删除重复项,请将test设为一个集合

test = [4, 6, 9, 4, 3, 88, 3, 2]
fourth = sorted(set(test))[-4]
print(fourth)

打破一切:

test=[4, 6, 9, 4, 3, 88, 3, 2] 
test = set(test) # Converting to set to get only unique numbers
test = list(test) # Converting back to list
test.sort(reverse = True) # Sorting in decreasing order
if len(test) >= 4: # Checking whether 4th element exists or not
    print(test[3]) # Printing 4th largest element
else:
    print("Not enough elements")

您可以像这样使用heapq.nlargest

>>> heapq.nlargest(4, test)[-1]
4

对于小列表,这可能比排序慢,但在一般情况下它应该表现更好,因为它不需要对完整列表进行排序。 不过,我还没有测试性能与排序的关系。

暂无
暂无

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

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