Python 如何将嵌套for循环编写为一行程序?

Python 如何将嵌套for循环编写为一行程序?,python,python-3.x,Python,Python 3.x,以下是我的功能: def find_how_many_pumpkins_are_needed_to_feed_animals(animal_list: list) -> int: """ Find how many pumpkins are needed to feed all herbivorous and omnivorous animals in the Zoo. For the sake of this calculation

以下是我的功能:

def find_how_many_pumpkins_are_needed_to_feed_animals(animal_list: list) -> int:
    """
    Find how many pumpkins are needed to feed all herbivorous and omnivorous animals in the Zoo.

    For the sake of this calculation, let's assume that there are 2 animals of each type at our zoo and each animal eats
    (on average) 6% of their body weight (average of values in the weight range) worth of pumpkins every day.
    One pumpkin weighs 3kg.
    Let's also assume that we are feeding the animals over the course of one 3-month-long winter (90 days)

    :param animal_list: input list
    :return: amount of pumpkins needed to sustain all the animals over the winter (rounded up).
    """
    cnt=0
    for i in range(90):
        for animal in animal_list:
            if animal.diet == "herbivorous" or animal.diet == "omnivorous":
                cnt += 2*(((animal.weight_range[0] + animal.weight_range[1]) / 2) * 0.06)
    return math.ceil(cnt/3) 

如果我想将嵌套for循环创建为一个一行程序,我该怎么做呢?

因为您只是对值求和,所以可以使用
sum
函数和一个生成器函数(也可以将循环运行90次,然后除以3,但循环不依赖于索引,所以应该将值乘以30)。您还可以提取一些乘法:

math.ceil(总和(((动物体重范围[0]+动物体重范围[1])/2)*0.06(动物名单中的动物)*30*2*0.06)
在这里,它以更可读的方式格式化:

math.ceil(
总数(
((动物体重范围[0]+动物体重范围[1])/2)*0.06
用于动物列表中的动物
)
* 30 * 2 * 0.06
)

由于您只是对值求和,因此可以使用
sum
函数和生成器函数(也可以运行循环90次,然后除以3,但循环不依赖于索引,因此您只需将值乘以30)。您还可以提取一些乘法:

math.ceil(总和(((动物体重范围[0]+动物体重范围[1])/2)*0.06(动物名单中的动物)*30*2*0.06)
在这里,它以更可读的方式格式化:

math.ceil(
总数(
((动物体重范围[0]+动物体重范围[1])/2)*0.06
用于动物列表中的动物
)
* 30 * 2 * 0.06
)

与您的函数等效的一行代码可以是:

result=math.ceil((如果动物饮食为“草食性”、“杂食性”),[2*((动物体重范围[0]+动物体重范围[1])/2)*0.06)(如果动物饮食为“草食性”、“杂食性”)))*90)/3)

与您的函数等效的一行代码可以是:

result=math.ceil((如果动物饮食为“草食性”、“杂食性”),[2*((动物体重范围[0]+动物体重范围[1])/2)*0.06)(如果动物饮食为“草食性”、“杂食性”)))*90)/3)

为什么要这样做?只是为了学习:)为什么要这样做?只是为了学习:)