Removing Negative Elements in a List - Python

不问归期 提交于 2020-06-27 15:24:26

问题


So, I`m trying to write a function that removes the negative elements of a list without using .remove or .del. Just straight up for loops and while loops. I don`t understand why my code doesn`t work. Any assistance would be much appreciated.

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

回答1:


A note to your code:

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]

Other mistakes:

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

A running code would be:

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

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




回答2:


Why not use list comprehension:

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

Examples

>>> 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]

As for your version, you are changing the elements of the list while iterating through it. You should absolutely avoid it until you are absolutely sure what you are doing.

As you state that this is some sort of exercise with a while loop, the following will also work:

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



回答3:


You could also use filter, if you so please.

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


来源:https://stackoverflow.com/questions/22976568/removing-negative-elements-in-a-list-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!