【问题标题】:Is there a pretty way to yield if in Python 3.3?如果在 Python 3.3 中,有没有一种很好的方法来让步?
【发布时间】:2013-03-16 19:39:06
【问题描述】:

有没有办法让这段代码更漂亮?

强 = li.find_all("强") 如果强: 产量 li.find_all("强")

我的意思是这样的:

强 = li.find_all("强") yield li.find_all("strong") if strong

【问题讨论】:

  • 如何更好地隐藏条件?
  • 这两者是否相等取决于li.find_all 执行/返回的内容,但通常不会写成strong = li.find_all("strong")if strong: yield strong?在我看来,唯一“不漂亮”的部分是重复(我猜这可能是必要的。)

标签: python python-3.x generator yield


【解决方案1】:

你可以这样做:

strong = li.find_all("strong")
strong and (yield strong)

它简洁漂亮,但在调试过程中可能很难理解它的作用。

【讨论】:

    【解决方案2】:

    你会使用:

    strong = li.find_all("strong")
    if strong:
        yield strong
    

    而不是再次调用find_all()(在 BeautifulSoup 中,它给出了相同的结果,但再次工作)。

    没有“条件收益”。你可以和yield from 玩花样,但我不建议这样做。

    【讨论】:

    • 哦,哇,我错过了我两次使用相同方法的事实。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-21
    • 2020-03-30
    • 2022-10-23
    • 1970-01-01
    • 2012-04-17
    相关资源
    最近更新 更多