gpt4 book ai didi

Python如果循环每次迭代产生相同的输出字符串,如何只打印一次?

转载 作者:行者123 更新时间:2023-12-01 05:54:59 24 4
gpt4 key购买 nike

a = [['jimmy', '25', 'pancakes'], ['tom', '23', 'brownies'], ['harry', '21', 'cookies']]
for i in range(len(a)):
if (a[i][1] == '20' or a[i][1] == '26'):
print 'yes'
else:
print 'Not found'

此输出出现 3 次未找到。如果 if 循环的每次迭代的输出都相同,我希望它迭代整个列表,然后仅打印一次 Not found

如果我更改 a[i][1] == '25' 并且输出变为:

yes
Not found
Not found

我想打印yes,但不想打印Not found

最佳答案

您可能正在寻找for-else循环。

正如 @Burhan Khalid 建议使用 for i in a 而不是 if range(len(a)):

a = [['jimmy', '25', 'pancakes'], ['tom', '23', 'brownies'], ['harry', '21', 'cookies']]
for i in a:
if (i[1] == '25' or i[1] == '26'):
print 'yes'
else:
print 'Not found'

输出:

yes
Not found

或者您可能正在寻找any():

In [200]: if any((i[1]=='25' or i[1]=='26') for i in a):
print 'yes'
else:
print 'not Found'
.....:


yes

In [204]: if any((i[1]=='20' or i[1]=='26') for i in a):
print 'yes'
else:
print 'not Found'
.....:


not Found

关于Python如果循环每次迭代产生相同的输出字符串,如何只打印一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13052695/

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