从列表中删除负元素 - Python

3

所以,我正在尝试编写一个函数,使用for循环和while循环直接删除列表的负元素,而不使用.remove或.del。但我不明白为什么我的代码不起作用。任何帮助都将不胜感激。

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

1
你在迭代时改变了列表。 - anthony sottile
3个回答

5
为什么不使用列表推导式:
new_list = [i for i in old_list if i>=0]

例子

>>> old_list = [1,4,-2,94,-12,-1,234]
>>> new_list = [i for i in old_list if i>=0]
>>> print new_list
[1,4,94,234]

关于你的版本,你在遍历列表时更改了列表元素。除非你完全确定自己在做什么,否则应该绝对避免这样做。

由于你说这是一种使用while循环的练习,以下代码也可以正常工作:

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

我必须使用同一个列表。我必须对其进行迭代。 - Tahmoor Cyan
当你执行L = L[:subscript] + L[subscript:]时,你已经在创建一个新的列表。如果你像这样调用函数:L = rmNegatives(L),那么你也在这里创建了一个新的列表。你真的确定需要保持相同的对象吗? - Fury
@Fury,但我并没有使用L = L[:subscript] + L[subscript:] - sshashank124
@ToxicTechnetium,如果我的回答有帮助,请您考虑采纳它吗?谢谢。 - sshashank124

4
如果您愿意,您还可以使用过滤器。
L = filter(lambda x: x > 0, L)

1

你的代码注释:

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

不改变你的列表。例如。
>>> 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 的解决方案,他们提供了更好的实现方法来解决你的问题...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接