【问题标题】:Deleting negative numbers from a list [duplicate]从列表中删除负数[重复]
【发布时间】:2021-04-16 18:13:05
【问题描述】:

我正在尝试执行一个函数,该函数从外部给出的列表中删除负数并返回新列表。但是我的代码给了我 "IndexError: list index out of range" 错误。我该如何解决?

class Prtc:
def __init__(self, x, _lst):
    self.x = x
    self._lst = _lst
    
def del_neg(self, _lst):
    i = 0
    while i < len(_lst):
        if _lst[i] < 0:
            _lst.remove(i)
        i += 1
    return _lst

【问题讨论】:

标签: python list function


【解决方案1】:

问题是每次删除 i 时实际上都会缩短列表,这是一个快速修复:

class Prtc:
    def __init__(self, x, _lst):
        self.x = x
        self._lst = _lst
        
    def del_neg(self, _lst):
        i = 0
        while i < len(_lst):
            if _lst[i] < 0:
                _lst.remove(_lst[i])
                i -= 1
            i += 1
        return _lst

也就是说,有很多更有效的方法来做到这一点:

def del_neg(self, _lst):
    return [item for item in _lst if item >= 0]

【讨论】:

    【解决方案2】:

    正如LPR 所说,问题是每次删除项目时都会缩短列表。在不过多使用索引的情况下可以做到这一点的通常方法是相反的:

    class Prtc:
    def __init__(self, x, _lst):
        self.x = x
        self._lst = _lst
        
    def del_neg(self, _lst):
        i = len(_lst) - 1
        while i >= 0:
            if _lst[i] < 0:
                _lst.remove(i)
            i -= 1
        return _lst
    

    虽然如果你不需要手动完成,你应该使用他的第二个代码,这是最pythonic的方式

    【讨论】:

      猜你喜欢
      • 2014-01-24
      • 2012-11-13
      • 2014-07-31
      • 2014-09-30
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 2011-01-13
      相关资源
      最近更新 更多