一个线性条件,多个变量并检查它们是否都不是假的?

One liner conditional, multiple variables and check that all of them are not false?

我如何在 python 中创建一个条件来检查字典中定义的这三个关键字并且它们不是 False

settings = {
    'proxy_host': '127.0.0.1',
    'proxy_port': 8080,
    'proxy_protocol': 'socks',
}

我试过你可以在下面看到的句子。但这只是检查字典中是否存在这些关键字 settings,而不关心值的类型。

if 'proxy_host' and 'proxy_port' and 'proxy_protocol' in settings:

我只希望我的 IF 为 True 如果 none 个关键字是错误的并且它们都作为键存在。

使用简单的生成器表达式和all():

if all(d.get(k) for k in keys):

示例:

keys = ['proxy_host', 'proxy_port', 'proxy_protocol']
if all(settings.get(k) for k in keys):
    print("Settings good!")
else:
    print("Missing setting!")
if ('proxy_host' in settings and isinstance(settings['proxy_host'], str)) 
   and ('proxy_port' in settings and isinstance(settings['proxy_port'], int)) 
   and ('proxy_protocol' in settings and isinstance(settings['proxy_protocol']), str)):

如果你想检查所有的键都在字典中并映射到一个非假值,你可以检查这个:

if all(settings.get(x) for x in ['proxy_host','proxy_port', 'proxy_protocol']):

dict.get(key) 会 return None 如果密钥不在 dict, 所以你可以一次性检查 "is in the dict and value is not falsey".