【问题标题】:Removing headline from allheadlines if headline has keyerror如果标题有 keyerror,则从所有标题中删除标题
【发布时间】:2019-12-02 10:55:27
【问题描述】:

我有一个 rss 提要标题列表,我正在像这样迭代:

for hl in allheadlines:
    try:
        updated = hl[0]['updated_parsed']
    except(KeyError):
        print("updated_parsed not in this headline")
        allheadlines.remove(hl)

我需要检查updated_parsed 是否在每个标题中,如果缺少,请完全删除该标题。上面的代码运行并打印“updated_pa​​rsed not in this heading”,但没有删除标题。知道为什么吗?

【问题讨论】:

标签: python python-3.x list for-loop


【解决方案1】:

如果您在使用for 循环时尝试从列表中删除元素,Python 大部分时间都会给您带来意想不到的结果。问题是 Python 保留了一个变量来记住当前元素,当列表从迭代器下发生变化时,它将引用一些意想不到的东西。

解决方案可能是迭代列表的副本:

for hl in allheadlines[:]:
    ...

或者您可以将列表迭代到前面:

for hl in reversed(allheadlines):
    ....

或者您可以创建第二个列表,您可以在其中放置符合您所需条件的所有元素。

【讨论】:

    【解决方案2】:

    for 循环中添加或删除元素,在循环中迭代此类列表会在 Python 中产生未定义的行为。

    许多可能的解决方案之一是创建单独的更新标题列表:

    updated_headlines = []
    for hl in allheadlines:
        try:
            updated = hl[0]['updated_parsed']
            updated_headlines.append(hl)
        except(KeyError):
            print("updated_parsed not in this headline")
    

    代码抛出异常在一行

    updated = hl[0]['updated_parsed']
    

    所以当它抛出下一行时:

    updated_headlines.append(hl)
    

    省略,不添加有错误的标题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-25
      • 1970-01-01
      • 2021-09-17
      • 2015-04-28
      • 1970-01-01
      • 2020-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多