列表中第四大元素的Python程序?
我已经编写了代码,但它显示第四大元素的输出不正确。让我知道我该怎么办?
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])
回答
您非常接近您可以使用内置排序函数并获取返回值的 [-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)