Pythonic方法检查kwargs中的所有值是否为字符串" false"

时间:2016-05-10 14:47:12

标签: python python-3.4

kwargs即:send_memberssend_companiessend_reviewers,其中每个包含字符串'true''false'

如果 all 每个kwargs中的值都是'false',我想显示错误消息,例如:

if (kwargs['send_members'] == 'false' and kwargs['send_companies'] == 'false' and
    kwargs['send_reviewers'] == 'false'):
        raise SomeError('at least one keyword needs to be true')

是否有Pythonic方式检查kwargs中的所有值是否相同,'false'?虽然上面的示例有效,但当我有10 kwargs时,它会变得非常混乱。

3 个答案:

答案 0 :(得分:5)

使用all()

if all(v == 'false' for v in kwargs.values()):
    print("All kwargs are false")

答案 1 :(得分:0)

kwargs = {'send_members':'false', 'send_companies':'false', 'send_reviewers':'false'}

def v1 ():
    if set(kwargs.values()) == {'false'}:
    return 'all false!'

def v2 ():
    if not [x for x in kwargs.values() if x !='false']:
    return 'all false!'

def v3 ():
    if all(v == 'false' for v in kwargs.values()):
    return 'all false!'


In [10]: %timeit -n100 v1()
100 loops, best of 3: 1.05 µs per loop

In [11]: %timeit -n100 v2()
100 loops, best of 3: 961 ns per loop

In [12]: %timeit -n100 v3()
100 loops, best of 3: 10.3 µs per loop

有趣的是,使用all()似乎慢了10倍。

答案 2 :(得分:0)

你也可以[也]使用内置的any()函数,它可能比all()快一点,因为一旦检测到故障它就会停止检查。

class SomeError(Exception): pass

testcases = [
    {'send_members': 'true', 'send_companies': 'false', 'send_reviewers': 'false'},
    {'send_members': 'false', 'send_companies': 'true', 'send_reviewers': 'false'},
    {'send_members': 'false', 'send_companies': 'false', 'send_reviewers': 'false'},
]

for kwargs in testcases:
    print(kwargs, end=' ')
    try:
        if any(value != 'false' for value in kwargs.values()):
            raise SomeError('at least one keyword needs to be true')
    except SomeError:
        print("At least one kwarg is not 'false'")
    else:
        print("OK, all kwargs are 'false'")