删除列表中的负数-Python [英] Removing Negative Elements in a List - Python

查看:128
本文介绍了删除列表中的负数-Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在尝试编写一个无需使用.remove或.del即可删除列表中负面元素的函数.只是直接循环和while循环.我不明白为什么我的代码无法正常工作.任何帮助将不胜感激.

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

推荐答案

代码注释:

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

这篇关于删除列表中的负数-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆