首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >有没有办法用for循环来计算布尔函数中有多少真/假输出?

有没有办法用for循环来计算布尔函数中有多少真/假输出?
EN

Stack Overflow用户
提问于 2019-04-09 18:47:19
回答 2查看 232关注 0票数 0

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

代码语言:javascript
代码运行次数:0
运行
复制
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

我还想找到一种方法来计算当我放入一个随机的input_price和input_day时,循环中有多少真和假。

EN

回答 2

Stack Overflow用户

发布于 2019-04-09 18:50:31

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

代码语言:javascript
代码运行次数:0
运行
复制
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

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

如果这不是预期的行为,请评论,我们可以通过您希望获得的。

票数 0
EN

Stack Overflow用户

发布于 2019-04-09 18:52:23

您可以使用sum来计算for循环中的所有True,(True=1False=0):

代码语言:javascript
代码运行次数: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)

测试和输出:

代码语言:javascript
代码运行次数:0
运行
复制
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

希望这对你有帮助,如果你有更多的问题可以发表意见。:)

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

https://stackoverflow.com/questions/55591019

复制
相关文章

相似问题

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