python - 多个for循环,不满足条件只打印一次else

标签 python

循环中有一个循环,如果满足条件则运行一些代码。但是,如果不满足条件,我需要它来打印一些东西。虽然如果我将代码添加到任何位置,它会被打印多次。如果不满足条件,如何让它只打印一次?

some_list = {'a_list': [{'name': 'Tom', 'age': 25}, {'name': 'John', 'age': 25}, {'name': 'Val', 'age': 25}], 'b_list': [{'name': 'Don', 'age': 25}, {'name': 'Tim', 'age': 25}, {'name': 'San', 'age': 25}]}

findperson = 'San'

for i in some_list:
    for y in some_list[i]:
        if y['name'].lower() == findperson.lower():
            print('Friend found')
            break
else:            
    print('Friend not found')

最佳答案

您可以对内部循环使用any(并在外部循环中使用break)...

for i in some_list:
    if any(y['name'].lower() == findperson.lower() for y in some_list[i]):
        print('Friend found')
        break
else:            
    print('Friend not found')

...甚至整个事情:

if any(y['name'].lower() == findperson.lower() 
       for i in some_list for y in some_list[i]):
    print('Friend found')
else:            
    print('Friend not found')

如果你还需要实际的 friend ,你可以使用next:

for i in some_list:
    friend = next((y for y in some_list[i] if y['name'].lower() == findperson.lower()), None)
    if friend is not None:
        print('Friend found:', friend)
        break
else:            
    print('Friend not found')

也适用于嵌套生成器,如上面的any:

friend = next((y for i in some_list for y in some_list[i] 
                 if y['name'].lower() == findperson.lower()),
              None)
if friend is not None:
    print('Friend found:', friend)
else:            
    print('Friend not found')

关于python - 多个for循环,不满足条件只打印一次else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56024281/

相关文章:

Python:哪个 XML 解析器支持 DTD !ENTITY 定义?

python - 如何更改matplotlib中矩阵的行和列的大小

Python、Selenium 和 Chromedriver - 使用 find_element_by_id 的无限循环导致 CPU 问题

Python图像处理: Help needed for corner detection in preferably PIL or any relevant module

python - BeautifulSoup 从 Id 获取短信

python - PyQuery 如何将一个元素追加和重命名到它的每个子元素中

python - App Engine Datastore IN Operator - 如何使用?

python - 通过 SqlAlchemy 中的关联对象实现多对多、自引用、非对称关系(twitter 模型)

python - C++和Python之间的通信

python - ImportError : No module named twisted. persisted.styles