【问题标题】:Python if a loop produces same output string for each iteration, how to print only once?Python如果循环为每次迭代产生相同的输出字符串,如何只打印一次?
【发布时间】:2012-10-24 15:42:58
【问题描述】:
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

【问题讨论】:

    标签: python if-statement output


    【解决方案1】:

    也许你正在寻找for-else循环。

    正如@Burhan Khalid 建议的那样,如果range(len(a)) 则使用for i in 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
    

    【讨论】:

    • range(len(a)) 可以更好地设置为for i in a:,然后是if i[1] == '25 or i[1] == '26':
    • 谢谢!它解决了第一个问题。但是对于第二个问题,它仍然会打印一次Not found。我如何让它只打印yes 用于正匹配而没有打印负匹配?
    • 对于否定匹配什么也不打印,那你为什么要打印Not Found
    • @koogee 看到我编辑的答案可能就是你要找的。​​span>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    • 2021-12-01
    • 1970-01-01
    相关资源
    最近更新 更多