python - 从Python中的未知列表中删除负数

标签 python list python-3.x negative-number del

在 Python 中工作,如何编写代码以使用 for 循环和 if 语句从未知整数列表中删除负数?

def mod_lis (list):
    for i in range(len(list)):
        if list[i] < 0:
            del list[i]
    return list

最佳答案

您的代码的问题是您在 for 循环期间修改了列表。结果是,您以这种方式跳过元素,并很快得到一个 IndexError,因为您的列表已被缩短。

您可以使用此列表理解来做到这一点:

mylist = [val for val in mylist if val>=0]

关于python - 从Python中的未知列表中删除负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22856334/

相关文章:

python - Tensorflow 中的分类和连续交叉特征列

django - 遍历自定义模板标签传递的列表

C++ : List iterator not incrementable

mysql - Python3 : Escape MySQL values in programmatically built query

python - 如何获得列表的所有组合?

python - 如何在 Django 管理 ListView 中只显示一个对象?

python - 如何禁用错误消息 'print keyword can' t 用作 pycharm 中的 python 2' 中的标识符?

Python Convert 设置为列表,不断收到 TypeError : 'list' object is not callable

Python 代码有效,但 Eclipse 显示错误 - Syntax error while detecting tuple

python - 根据另一个数组设置 Numpy 数组中的值