Python列表元素

时间:2018-06-15 21:08:40

标签: python flask

我有一个带有以下输入验证例程的Flask控制器操作,有没有办法更简洁地写它?

if 'firstName' and \
    'lastName' and \
    'age' \
not in request.json:
    return flask.abort(400)

也许是这样的,虽然我不确定如何让运算符起作用:

mandatory_fields = ['firstName', 'lastName', 'age']
if mandatory_fields not in request.json:
        return flask.abort(400)

第二个代码段是否可行?

1 个答案:

答案 0 :(得分:1)

您可以使用all()这样的方法:

fields = ["a", "b", "c"]
a_hash = {"a": 1, "b": 2, "c": 3, "d": 4}
if all(field in a_hash for field in fields):
    print("All good")
# prints "All good"

fields = ["a", "b", "c", "e"]
a_hash = {"a": 1, "b": 2, "c": 3, "d": 4}
if any(field not in a_hash for field in fields):
    print("All bad")
# prints "All bad"