【问题标题】:Verify state of boolean variables in a dict验证字典中布尔变量的状态
【发布时间】:2016-08-16 09:56:34
【问题描述】:

我正在使用一些标志来跟踪以下操作:

is_registered = True
has_paid = False    
has_phone  = True

if (is_registered and has_phone and has_paid):
    do_something

但如果字段数量增加,我更愿意将其存储在字典中

user_flags = {'is_registered':True,'has_paid':False,'has_phone':True}

if (user_flags['is_registered'] and user_flags['has_paid'] and user_flags['has_phone']):
    do_something

再一次,这对于少量项目可能没问题,但如果我说超过 50 个项目,它就会变得非常冗长

【问题讨论】:

  • 你到底想做什么? and 一堆存储在字典中的布尔变量?

标签: python dictionary boolean


【解决方案1】:

你可以使用all():

>>> user_flags = {'is_registered':True, 'has_paid':False, 'has_phone':True}
>>> all(user_flags.values())
False

>>> user_flags = {'is_registered':True, 'has_paid':True, 'has_phone':True, 'one_more_flag':True}
>>> all(user_flags.values())
True

或者,用any()反转逻辑:

>>> user_flags = {'is_registered':True, 'has_paid':False, 'has_phone':True}
>>> not any(not value for value in user_flags.values())
False

>>> user_flags = {'is_registered':True, 'has_paid':True, 'has_phone':True, 'one_more_flag':True}
>>> not any(not value for value in user_flags.values())
True

【讨论】:

  • 不需要genexp; all(user_flags.values()) 会做同样的事情。
  • @user2357112 我的错。谢谢!
【解决方案2】:

这取决于您希望在if 行中保持可见的信息类型。 一个“完全可见性”选项可能是,

def check_flags(user, flags):
    return all([user[flag] for flag in flags])

user_flags = {'is_registered':True,'has_paid':False,'has_phone':True}

if check_flags(user_flags, ['is_registered', 'has_paid', 'has_phone']):
    do_something()

如果您不介意重新搜索您正在检查的标志,只需将标志嵌入到函数中并执行if user_is_ready(): 即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-24
    相关资源
    最近更新 更多