2016-06-21 94 views
1

我有一个元组列表,我在一个简单的循环中循环来识别包含一些条件的元组。Python在“IF ELSE”循环中使用“IN”

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 

回答

7

您应该使用内置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') 
+2

IMO这是我们如何做相反,例如,'如果项目[1] =“ABC”和任何的最佳方式 – Andrew

+0

(关键字在项目[2]关键字在关键字):'得到元组3和4? – jxn

+0

@jxn好吧,这会给你元组3:'如果项目[1]!='ABC'和全部(关键字不在关键字的项目[2]中):'。基本上,我们要求所有关键字不匹配。 – alecxe

3

你不这样做,因为in与一个序列只匹配整个元素。

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

你的第二个方法(其中,然而,需要被加上括号为x and (y or z)是正确的)是必要的tup[2]包含您的一个关键短语,而不是您的一组键短语。你可以使用正则表达式匹配在一些性能:

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