gpt4 book ai didi

Python 在 "IN"循环中使用 "IF ELSE"

转载 作者:太空宇宙 更新时间:2023-11-04 06:54:44 25 4
gpt4 key购买 nike

我有一个元组列表,我在一个简单的 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

最佳答案

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

关于Python 在 "IN"循环中使用 "IF ELSE",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37952418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com