且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

删除列表中的负数-Python

更新时间:2023-02-10 14:23:09

代码注释:

L = L[:subscript] + L[subscript:]

不会更改您的列表.例如

does not change your list. For example

>>> l = [1,2,3,4]
>>> l[:2] + l[2:]
[1, 2, 3, 4]

其他错误:

def rmNegatives(L):
    subscript = 0
    for num in L: # here you run over a list which you mutate
        if num < 0:
            L = L[:subscript] + L[subscript:] # here you do not change the list (see comment above)
        subscript += 1 # you have to do this only in the case, when you did not remove an element from the list
    return L

正在运行的代码为:

def rmNegatives(L):
    subscript = 0
    for num in list(L):
        if num < 0:
            L = L[:subscript] + L[subscript+1:]
        else:
            subscript += 1
    return L

请参阅@Aesthete和@ sshashank124的解决方案,以更好地解决您的问题...

See the solutions of @Aesthete and @sshashank124 for better implementations of your problem...