代码之家  ›  专栏  ›  技术社区  ›  Taohidul Islam

如何简化if子句中的多个条件?

  •  0
  • Taohidul Islam  · 技术社区  · 6 年前

    我已经写了一段代码 Django 比如:

    phone = request.data.get("phone")
    password = request.data.get("password")
    age = request.data.get("age")
    name = request.data.get("name")
    
    if not phone or not password or not age or not name: #multiple not checks
        return Response({"status": False})
    

    not

    2 回复  |  直到 6 年前
        1
  •  1
  •   JPG    6 年前

    你的 request.data 请求.数据 是强制性的。

    all() 作为

    if not all([True if v else False for k, v in request.data.items()]):
        return Response({"status": False})

    phone , password

    假设您有特定的字段,例如 myfields = ['username','password','name','age'] 全部()

    myfields = ['username', 'password', 'name', 'age']
    if not all([True if request.data.get(k) else False for k in myfields]):
        return Response({"status": False})
        2
  •  4
  •   adrg    6 年前

    您不允许任何内容是可选的或空的,因此您可以执行以下操作:

    if not (phone and password and age and name):
        return Response({"status": False})