首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python中的列表元素

Python中的列表元素
EN

Stack Overflow用户
提问于 2018-06-16 05:08:40
回答 1查看 35关注 0票数 0

我有一个带有以下输入验证例程的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)

第二个代码片段可能吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-16 05:13:11

您可以像这样使用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"
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50882680

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档