Python使用;在;在“a”中;如有其他",;环
我有一个元组列表,在一个简单的for循环中循环,以识别包含一些条件的元组Python使用;在;在“a”中;如有其他",;环,python,loops,operators,Python,Loops,Operators,我有一个元组列表,在一个简单的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:
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
不需要,因为序列中的
只匹配整个元素
if tup[1] =='ABC' and any(el in tup[2] for el in ('Today is', 'The sky')):
不需要,因为序列中的只匹配整个元素
if tup[1] =='ABC' and any(el in tup[2] for el in ('Today is', 'The sky')):
您应该使用内置功能:
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')
您应该使用内置功能:
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')
您的第二种方法(需要插入括号,作为x和(y或z)
才能正确)是必要的tup[2]
包含一个关键短语,而不是一组关键短语的元素。您可以使用正则表达式匹配,但要牺牲一些性能:
if tup[1] == 'ABC' and re.match('Today is|The sky', tup[2])
您的第二种方法(需要插入括号,作为x和(y或z)
才能正确)是必要的tup[2]
包含一个关键短语,而不是一组关键短语的元素。您可以使用正则表达式匹配,但要牺牲一些性能:
if tup[1] == 'ABC' and re.match('Today is|The sky', tup[2])
在我看来,这是最好的方法,我们如何做相反的事情,例如,if item[1]!='ABC'和any(关键字中的关键字对应于关键字中的关键字):
要获取元组3和4?@jxn好的,这将为您提供元组3:如果项目[1]!='ABC'和all(关键字中的关键字不在[2]项中):
。基本上,我们要求所有关键字都不匹配。在我看来,这是最好的方法。我们如何做相反的事情,例如,if item[1]!='ABC'和any(关键字中的关键字对应于关键字中的关键字):
要获取元组3和4?@jxn好的,这将为您提供元组3:如果项目[1]!='ABC'和all(关键字中的关键字不在[2]项中):
。基本上,我们要求所有关键字不匹配。