【问题标题】:One liner conditional, multiple variables and check that all of them are not false?一个班轮条件,多个变量并检查它们是否都不是假的?
【发布时间】:2015-08-18 22:19:39
【问题描述】:

如何在 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。

【问题讨论】:

  • 您使用的是哪个版本的 Python?
  • 您的if 语句没有检查这些关键字是否是字典settings 的关键字。试试这个:print('a' and 'b' and 'proxy_host' in settings)。它将打印 True,因为 'a' 为 True,'b' 为 True,'proxy_host' in settings 为 True。
  • If none of the keywords are False - 这是什么意思?
  • @thefourtheye:我很确定 JesúsFlores 的意思是“如果与这些关键字关联的 都不是 False”。
  • 是的,我错了,我说的是字典键值...

标签: python if-statement conditional conditional-statements


【解决方案1】:
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)):

【讨论】:

  • 公平调用,即使 OP 没有询问该程度的数据验证。此外,避免类型检查被认为更像 Pythonic,除非绝对必要,因为它会干扰duck typing
  • 是的,你是对的。编辑了我的帖子。我认为是可行的,因为操作有这条线:But...without bothering about what type of value has
  • 哈哈,你们真聪明!真的。我认为您的回答在技术上是最好的。但我已经要求一个班轮。也许社区应该通过投票来奖励/感谢你,我做到了;)非常感谢!
【解决方案2】:

使用简单的生成器表达式和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!")

【讨论】:

  • 一段非常漂亮的代码,但我仍然收到True,即。 proxy_port 是一个空字符串(应该评估为 False)...
  • @JesúsFlores 啊!见更新。基本上你想“尝试”从你的设置中获取一堆键 dict 并默认为 None 如果它们不存在则评估“错误”。
  • 你是第一个回答这个问题的人。所以荣誉归于你:) 正如@PM2Ring 所建议的,我使用了一个元组,因为它们是不可变的。谢谢!!!
  • 别担心!感谢您使用 Stackoverflow :)
【解决方案3】:

如果要检查所有键是否都在 dict 中并映射到非假值,可以检查:

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

如果键不在dict 中,dict.get(key) 将返回None,因此您可以一次性检查“在字典中且值不是假的”。

【讨论】:

  • 很好,虽然我可能会使用元组而不是键列表。
  • 太棒了,很抱歉詹姆斯是第一个回答的。我用过元组;)
猜你喜欢
  • 2014-03-05
  • 2023-04-01
  • 1970-01-01
  • 2014-09-01
  • 2012-11-16
  • 2020-07-17
  • 2023-01-19
  • 1970-01-01
  • 2011-01-03
相关资源
最近更新 更多