【问题标题】:Python using "IN" in a "IF ELSE" loopPython 在“IF ELSE”循环中使用“IN”
【发布时间】:2016-10-23 11:22:20
【问题描述】:

我有一个元组列表,我在一个简单的 for 循环中循环以识别包含某些条件的元组。

    mytuplist = 
    [(1, 'ABC', 'Today is a great day'), (2, 'ABC', 'The sky is blue'), 
     (3, 'DEF', 'The sea is green'), (4, 'ABC', 'There are clouds in the sky')]

我希望它像这样高效且可读:

    for tup in mytuplist:
        if tup[1] =='ABC' and tup[2] in ('Today is','The sky'):
            print tup

上面的代码不起作用,什么也没有打印出来。

下面的代码有效,但非常罗嗦。我如何使它像上面那样?

for tup in mytuplist:
    if tup[1] =='ABC' and 'Today is' in tup[2] or 'The sky' in tup[2]:
        print tup

【问题讨论】:

    标签: python loops operators


    【解决方案1】:

    你应该使用内置的any()函数:

    mytuplist = [
        (1, 'ABC', 'Today is a great day'),
        (2, 'ABC', 'The sky is blue'),
        (3, 'DEF', 'The sea is green'),
        (4, 'ABC', 'There are clouds in the sky')
    ]
    
    keywords = ['Today is', 'The sky']
    for item in mytuplist:
        if item[1] == 'ABC' and any(keyword in item[2] for keyword in keywords):
            print(item)
    

    打印:

    (1, 'ABC', 'Today is a great day')
    (2, 'ABC', 'The sky is blue')
    

    【讨论】:

    • imo这是最好的方法
    • 我们如何反其道而行之,例如if item[1] != 'ABC' and any(keyword in item[2] for keyword in keywords):得到元组3和4?
    • @jxn 好吧,这会给你元组 3:if item[1] != 'ABC' and all(keyword not in item[2] for keyword in keywords):。基本上,我们要求所有关键字不匹配。
    【解决方案2】:

    你没有,因为带有序列的in 只匹配整个元素。

    if tup[1] =='ABC' and any(el in tup[2] for el in ('Today is', 'The sky')):
    

    【讨论】:

      【解决方案3】:

      您的第二种方法(但是,需要用括号括起来为 x and (y or z) 才能正确)是必需的 tup[2] 包含您的关键短语之一,而不是您的集合中的一个元素的关键短语。您可以以牺牲一些性能为代价使用正则表达式匹配:

      if tup[1] == 'ABC' and re.match('Today is|The sky', tup[2])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-15
        • 2015-10-28
        • 1970-01-01
        相关资源
        最近更新 更多