python - 删除函数更改不相关的 for 循环的元素 (Python)

标签 python

我尝试删除数据库中小于所选字符 i 的所有字符。数据库是字符列表的列表。

def project(database, i):
    test = database.copy()
    for idx,lists in enumerate(database.copy()):
        for char in lists:
            print(char)
            if char <= i:
                test[idx].remove(char)
     return test

a = [['A','B','D'],['A','B','C','D']]
print(project(a, 'C'))


Output:
A D A C
[['B', 'D'], ['B', 'D']]

不知何故,代码从不检查“B”,尽管它在列表中。没有 if 条件 + 删除行(第 5-6 行)的相同代码执行以下操作:

Output:
A B D A B C D
['A', 'B', 'D'], ['A', 'B', 'C', 'D']]

为什么我不改变迭代列表,打印的字符却改变了?

最佳答案

调试后:

问题不是因为您的 if 语句,而是因为删除更改了索引。

让 mt 证明:

  • 第一次迭代并删除 A 后,列表将是:

    ["B", "D"]
    

您的索引将为 1,因为 "B" 将被忽略。

关于python - 删除函数更改不相关的 for 循环的元素 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45928858/

相关文章:

python - MySQL——使用 Python 连接不同服务器上的数据库?

python - 在python脚本中访问共享的smb ubuntu

python - openssl hmac 与 python hmac 不同

python - 使用 Django 时如何隐藏 Pylint 1.2.1 错误输出?

python - 运行测试用例后如何保存django测试数据库

python - Savitzky-Golay 过滤器的 Scipy 实现

python - 使用 boto3 连接 CloudFront 时如何选择 AWS 配置文件

python - 如何在pandas数据框中生成动态变量名称

Python 多处理 : AttributeError: Can't pickle local object

python - flask 棉花糖去掉小数点