首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在不调用所有比较的情况下迭代if语句?

如何在不调用所有比较的情况下迭代if语句?
EN

Stack Overflow用户
提问于 2018-05-23 00:36:15
回答 2查看 38关注 0票数 0

我有一些固定的变量,我想与一些用户输入进行比较。根据结果,我想打印一个结果,但是如何比较变量,而不调用许多if语句,并且必须将每个语句相互比较?

代码语言:javascript
复制
#Nutrition Class and methods

class Nutrition():
    def __init__(self):
        self.pro = pro
        self.vit = vit
        self.carb = carb
        self.fat = fat
        self.mineral = mineral

    def comp_nut(self, pro, vit, fat, carb, mineral):
        if(self.pro >= req_pro) and (self.vit>= req_vit) and (self.fat >= req_fat) and (self.carb >= req_carb) and (self.mineral >= req_min):
            print("You are healthy")
        elif (self.pro >= req_pro) and (self.vit>= req_vit) and (self.fat >= req_fat) and (self.carb >= req_carb) and (self.mineral < req_min):
            print("Mineral is low!")
            print("Require Amount is "+ str(req_min))
        elif (self.pro >= req_pro) and (self.vit>= req_vit) and (self.fat >= req_fat) and (self.carb < req_carb) and (self.mineral >= req_min):
            print("Carb is low!")
            print("Require Amount is "+ str(req_carb))
        elif (self.pro >= req_pro) and (self.vit>= req_vit) and (self.fat < req_fat) and (self.carb >= req_carb) and (self.mineral >= req_min):
            print("Fat is low!")
            print("Require Amount is "+ str(req_fat))
        elif (self.pro >= req_pro) and (self.vit < req_vit) and (self.fat >= req_fat) and (self.carb >= req_carb) and (self.mineral >= req_min):
            print("Vitamin is low!")
            print("Require Amount is "+ str(req_vit))
        elif (self.pro < req_pro) and (self.vit>= req_vit) and (self.fat >= req_fat) and (self.carb >= req_carb) and (self.mineral >= req_min):
            print("Protein is low!")
            print("Require Amount is "+ str(req_pro))
        else:
           print('More than 1')

# User Input

pro = int(input("Enter Protein: "))
vit = int(input("Enter Vitamin: "))
fat = int(input("Enter Fat: "))
carb = int(input("Enter Carbs: "))
mineral = int(input("Enter Mineral: "))
EN

回答 2

Stack Overflow用户

发布于 2018-05-23 00:50:20

一次测试一件事,如下所示:

代码语言:javascript
复制
def comp_nut(self, pro, vit, fat, carb, mineral):
    if (self.mineral < req_min):
        print("Mineral is low!")
        print("Require Amount is "+ str(req_min))
    elif (self.carb < req_carb):
        print("Carb is low!")
        print("Require Amount is "+ str(req_carb))
    elif (self.fat < req_fat):
        print("Fat is low!")
        print("Require Amount is "+ str(req_fat))
    elif (self.vit < req_vit):
        print("Vitamin is low!")
        print("Require Amount is "+ str(req_vit))
    elif (self.pro < req_pro):
        print("Protein is low!")
        print("Require Amount is "+ str(req_pro))
    else:
        print("You are healthy.")

这将打印缺陷检查成功的第一条消息,或"You are healthy“。如果所有检查都失败。

票数 1
EN

Stack Overflow用户

发布于 2018-05-23 01:05:07

为了避免每次重复所有字段,我会这样做:

代码语言:javascript
复制
from collections import namedtuple

# Use a namedtuple so that we don't have to write __init__()
# and so that all the field names are stored in _fields.
class Nutrition(namedtuple('Nutrition', 'protein vitamin fat carb mineral')):

    # List of minimum requirement per each
    # field (these are random numbers)
    min_requirements = {
        'protein': 50,
        'vitamin': 60,
        'fat': 120,
        'carb': 30,
        'mineral': 40,
    }

    def check(self):
        healthy = False

        # Instead of checking the fields one by one,
        # use a loop over _fields.
        for field in self._fields:
            value = getattr(self, field)
            expected = self.min_requirements[field]
            if value < expected:
                print('{} is low!'.format(field.capitalize()))
                print('Required amount is {}'.format(expected))
                healthy = False

        if healthy:
            print('You are healthy')

示例用法:

代码语言:javascript
复制
n = Nutrition(
    protein=int(input('Enter Protein: ')),
    vitamin=int(input('Enter Vitamin: ')),
    fat=int(input('Enter Fat: ')),
    carb=int(input('Enter Carbs: ')),
    mineral=int(input('Enter Mineral: ')),
)

n.check()

这样做的好处是,如果您想要添加/删除一个字段,这是一个微不足道的更改。此外,如果您想添加更复杂的条件(例如,检查最大值而不仅仅是最小值),这也是一个微不足道的变化。

我使用namedtuple主要是为了缓解懒惰。这有一个副作用,即您的字段是只读的,但即使没有namedtuple,您也可以简单地获得相同的结果。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50472620

复制
相关文章

相似问题

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