python - 验证字典中 boolean 变量的状态

标签 python dictionary boolean

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

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 个项目,它会变得非常冗长

最佳答案

您可以使用 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

关于python - 验证字典中 boolean 变量的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36799409/

相关文章:

python - 使用来自文件的输入创建字典

java - 无法更改方法中的 boolean 值

android - 在android中放置额外的 boolean 值给出错误的值

python - 将小的 np.array 添加到更大的 np.array

python - 根据一段时间内的平均值对面板数据框中的项目进行分类

scala - 映射 groupBy 与多排序

python - 将字典中的键同步到列表中的多个值

python发送带有文本和附件的电子邮件

python - 路由请求字符串中的多个变量

google-app-engine - 如何将一个简单的 HTML 复选框变成 Google App Engine 上的 boolean 值?