删除列表中的否定元素 - Python

Tah*_*yan 3 python for-loop

因此,我试图编写一个函数来删除列表的负面元素,而不使用.remove或.del.只需直接进行循环和循环.我不明白为什么我的代码不起作用.任何援助将不胜感激.

def rmNegatives(L):
    subscript = 0
    for num in L:
        if num < 0:
            L = L[:subscript] + L[subscript:]
        subscript += 1
    return L
Run Code Online (Sandbox Code Playgroud)

ssh*_*124 5

为什么不使用列表理解:

new_list = [i for i in old_list if i>=0]
Run Code Online (Sandbox Code Playgroud)

例子

>>> 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]
Run Code Online (Sandbox Code Playgroud)

至于你的版本,你在迭代它时改变列表的元素.在你完全确定自己在做什么之前,你应该完全避免它.

当你声明这是带while循环的某种练习时,以下内容也会起作用:

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