有没有一种方法可以计算在一个带有for循环的布尔函数中有多少真/假输出?

2024-06-16 09:38:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python做关于航班价格的课程。我的布尔函数返回是现在购买机票还是等待更长时间购买机票,其中True表示现在购买,False表示等待更长时间:

def should_I_buy(data, input_price, input_day):
    """Returns whether one should buy flight ticket now or wait longer to buy"""
    for day, price in data:
        if day < input_day:
            if price < input_price:
                return False
    return True

我还想找到一种方法,当我输入一个随机的输入价格和输入日期时,计算循环中有多少对错。你知道吗


Tags: 函数falsetrueinputdatareturnif价格
2条回答

可以使用sum对for循环中的所有True进行计数,(True=1False=0):

def should_I_buy(data, input_price, input_day):
    """Returns whether one should buy flight ticket now or wait longer to buy"""
    return sum(day >= input_day or price >= input_price for day, price in data)

测试和输出:

data = [(14, 77.51), (13, 14.99), (12, 56.09), (11, 14.99), (10, 14.99), (9, 14.99), (8, 39.00), (7, 114.23),
        (6, 37.73), (5, 56.09), (4, 14.99), (3, 22.43), (2, 22.43), (1, 31.61), (0, 168.29)]

print(should_I_buy(data, 50.00, 8))   # output 10
print(should_I_buy(data, 18.00, 3))   # output 15

希望这对您有所帮助,如果您还有其他问题,请发表评论。:)

那么,您应该使用一个在每次迭代中递增的变量:

def should_I_buy(data, input_price, input_day):
    """Returns whether one should buy flight ticket now or wait longer to buy"""
    number_of_false = 0
    for day, price in data:
        if day < input_day:
            if price < input_price:
                number_of_false+=1
    return number_of_false,len(data)-number_of_false

NB

请注意,我不知道你在做什么,所以我的答案是基于快速查看你的代码。你知道吗

如果这不符合预期,请评论,我们可以通过您希望获得什么。你知道吗

相关问题 更多 >