删除列表Python中的否定元素

2024-09-28 16:57:25 发布

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

因此,我试图编写一个函数来删除列表中的负元素,而不使用.remove或.del。直接向上做循环和while循环。我不明白为什么我的代码不起作用。如有任何帮助,将不胜感激。在

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

Tags: 函数代码in元素列表forreturnif
3条回答

代码注释:

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

不会更改您的列表。例如

^{pr2}$

其他错误:

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

请参阅@aessette和@sshashank124的解决方案,以更好地实现您的问题。。。在

如果你愿意的话,你也可以用过滤器。在

L = filter(lambda x: x > 0, L)

为什么不使用列表理解:

new_list = [i for i in old_list if i>=0]

示例

^{pr2}$

对于您的版本,您在遍历列表的同时更改列表的元素。你应该绝对避免它,直到你确定你在做什么。在

当您声明这是一种使用while循环的练习时,以下内容也将起作用:

def rmNegatives(L):
    i = 0
    while i < len(L):
        if L[i]<0:
            del L[i]
        else:
            i+=1
    return L

相关问题 更多 >