第二个最大元素是lis

2024-09-28 17:28:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在列表中找到第二个max元素,我有一个重复案例的问题。为什么我的for循环没有删除list2(b)中max element的所有实例。for循环应该检查并删除所有重复实例。我在下面附上了我的代码。你知道吗

a=[]
b=[]
print "Enter the value of n\n"
n= int(raw_input())

print "enter the values\n"

for i in range(0,n):
    y = raw_input()
    a.append(int(y))

max = a[0]
for i in a:
    if max<i:
        max=i
y=max
a.remove(y)
b.append(y)

for q in a:
    for p in b:
        if q==p:
            a.remove(q)

max1 = a[0]
for i in a:
    if  max1<i:
        max1=i

print  max1

输出:

Enter value of n 
3
enter the values 
32
32
11
ans:11
Enter value of n 
4
enter the values
32
32
32
32
11
ans:32 (this is wrong)

Tags: ofthe实例inforrawifvalue
3条回答

代码的问题是,您在循环中遍历一个列表并从同一个列表中删除项,这将减少列表中的元素,并且无法按预期工作。你知道吗

问题是

for q in a:
    for p in b:
        if q==p:
            a.remove(q)

在这里,您迭代lista并删除循环块中的元素a.remove(q)

因此,在第一种情况下,32 32 11->;它可以正常工作,因为它删除32

但在第二种情况下,这不会删除第三个32,你会得到[32,11]在一个

第k个元素的搜索是一个众所周知的问题,有一系列的解决方案,可以在大约O(N)时间内解决它,请阅读https://en.wikipedia.org/wiki/Selection_algorithm

Python的标准库(从2.4开始)包括heapq.nsmallest()nlargest(),它们以O(nlogk)时间返回排序列表。你知道吗

就我个人而言,我宁愿用线性O(N)算法来解决你的问题:

topmost = max( a )    # select the largest one
filtered = [i for i in a if i != topmost]   # filter it out
second_best = max( filtered )   # here you have it!

您的问题是迭代a列表,并在这个循环中删除列表的元素。您不应该修改正在迭代的列表。你知道吗

您可以使用内置的python函数:set删除重复项,sorted排序

>>> a = [32, 32, 32, 32, 11]
>>> sorted(set(a), reverse=True)[1]
11

而且,你知道python2很快就不再是我了吗?如果可以的话,可以更改为python3。你知道吗

相关问题 更多 >