【问题标题】:How do I use boolean logic to make this if-statement more concise in python 3?如何使用布尔逻辑使这个 if 语句在 python 3 中更简洁?
【发布时间】:2020-12-23 22:16:26
【问题描述】:

我想从网站的 json 数据中提取包含“后端”、“后端”或“后端”的职位。我设法使用以下代码做到了这一点:

if "back-end" in jobtitle.lower():
            print(jobtitle)
if "back end" in jobtitle.lower():
            print(jobtitle)
if "backend" in jobtitle.lower():
            print(jobtitle)
else:
            continue

示例输出如下:

Software Back-End Developer
(Senior) Back-end PHP Developer
Backend Developer (m/w/d)
Back End Developer
Front-End / Back-End Developer (m/w/d)

如何让它更简洁?

【问题讨论】:

    标签: python python-3.x if-statement string-matching boolean-logic


    【解决方案1】:

    使用if ... in吗?另一种解决方案是使用regular expressions

    back[\-\s]?endTry it here

    解释:

    • back: 匹配“后退”
    • [\-\s]:这些字符中的任何一个:-<whitespace>
    • ?: 前面的零个或一个
    • end:匹配“结束”

    像这样在 Python 中运行它:

    rexp = re.compile(r"back[\s\-]?end", re.IGNORECASE)
    if re.search(rexp, jobtitle):
        print(jobtitle)
    

    【讨论】:

    • 我建议也使用re.IGNORECASE
    • 好点,虽然如果 OP 正在测试 jobtitle.lower() 无论如何都没关系。
    【解决方案2】:

    在这里使用正则表达式是最佳的,因为它速度很快,并且会在一行中解决它。

    但是,如果您想对每个选项使用if ... in 语句,则可以使用any() 在同一语句中比较它们:

    x = """Software Back-End Developer
    (Senior) Back-end PHP Developer
    Backend Developer (m/w/d)
    Back End Developer
    Front-End / Back-End Developer (m/w/d)""".splitlines()
    
    for row in x:
      if any(i in row.lower() for i in ["backend", "back end", "back-end"]):
        print(row)
    

    【讨论】:

      猜你喜欢
      • 2011-09-30
      • 2013-03-03
      • 2018-08-10
      • 1970-01-01
      • 1970-01-01
      • 2013-05-06
      • 1970-01-01
      • 2022-01-21
      相关资源
      最近更新 更多