Skip to main content
 首页 » 编程设计

python之Next() 跳过列表中的实际项和下一项,而它应该只跳过实际项

2025年05月04日15xxx_UU

我正在编写一个程序,给出一个整数列表,确定最小值,然后用列表的次要索引删除最小值。

例如:list = [3, 6, 15, 2, 4, 2] 应该返回 [3, 6, 15, 4, 2] 请注意,由于列表中的次索引,前 2 个被删除。

这是我的全部代码:

def remove_smallest(numbers): 
    mylist = [] 
    if not numbers: 
        return mylist  
    minimo = min(numbers) 
    if numbers.count(minimo) > 1: 
        numbers = numbers[::-1] #My solution to the minor index is to reverse the list and loop. Then reverse again. 
 
        #mylist = [item for item in numbers if item != minimo and item not in mylist]  #I tried to use a list comprehension, with awful results. 
 
        it = iter(numbers) 
        for item in it: 
            if item == minimo and item in mylist: 
                next(it, None) 
                continue 
            mylist.append(item) 
 
    print(mylist[::-1]) 
 
remove_smallest([2, 4, 5, 1, 2, 1]) 

前两项将附加到“mylist”(1, 2)。 然后,因为 1 在 mylist 上,它会跳过它然后继续。到目前为止一切顺利,但是当它应该选择 5 时,它没有,而是直接选择 4,然后选择 2,在程序结束时产生一个如下所示的数组:[2, 4, 2, 1 ] 当它应该返回 [2, 4, 5, 2, 1]

谢谢

请您参考如下方法:

一个简单的语句将删除最小值。 l.index(min(l)) 找到最小值的索引。

>>> l = [2,4,5,1,2,1] 
>>> del l[l.index(min(l))] 
>>> l 
[2, 4, 5, 2, 1]