【问题标题】:if statement not removing element from list Python3 [duplicate]if语句未从列表Python3中删除元素[重复]
【发布时间】:2021-02-18 04:19:54
【问题描述】:

我通过 subprocess.check_output 使用 bash 命令从 git 获取一些分支,对其进行解码、剥离,然后将其拆分为一个列表。

然后我将遍历列表以检查哪些分支不符合要求,如果是这种情况,则将它们从列表中删除。但由于某种原因,它没有按预期工作。

#Comes back as a bytes object with newlines after each branch name
git = subprocess.check_output(["git", "branch", "-r"])

branches = git.decode("utf-8").replace("origin/", "").strip("\n").split()

for branch in branches:
   if "LIVE" not in branch:
      branches.remove(branch)

print(branches)

最后,我希望分支会以空列表的形式返回,因为我知道没有一个分支包含“LIVE”,因此应该从列表中删除。但是,列表仍然每次返回 1/2 个元素,我不知道为什么。

【问题讨论】:

    标签: python python-3.x git


    【解决方案1】:

    迭代器实际上只是环绕列表中的索引。让我们举个例子,你有一个列表[1, 2, 3],它当前位于第一个元素上:

    [1, 2, 3]
     ^
    

    当你删除它然后继续循环时,迭代器将前进到第二个元素,但列表将向左移动:

    [2, 3]
        ^
    

    所以,迭代器基本上跳过了一个项目。您应该只使用列表推导所必须的过滤来避免这个问题:

    branches = [branch in branches if "LIVE" not in branch]
    

    【讨论】:

    • 啊当然!感谢您清除它。我不知道过滤列表的方法。
    猜你喜欢
    • 2018-04-20
    • 2015-01-05
    • 2012-05-09
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多