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

时间:2012-10-24 15:42:58

标签: python if-statement output

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'

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

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

yes
Not found
Not found

我想打印yes但不打印Not found

1 个答案:

答案 0 :(得分:2)

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

和@Burhan Khalid建议使用for i in a代替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