簡體   English   中英

如何將嵌套的 for 循環編寫為單行?

[英]How to write a nested for loop as a one liner?

這是我的功能:

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(sum(((animal.weight_range[0] + animal.weight_range[1]) / 2) * 0.06 for animal in animal_list) * 30 * 2 * 0.06)

這里以更易讀的方式格式化:

math.ceil(
    sum(
        ((animal.weight_range[0] + animal.weight_range[1]) / 2) * 0.06
        for animal in animal_list
    )
    * 30 * 2 * 0.06
)

相當於您的功能的一個班輪可能是:

result = math.ceil((sum([2 * (((animal.weight_range[0] + animal.weight_range[1]) / 2) * 0.06) for animal in animal_list if animal.diet in ("herbivorous", "omnivorous")]) * 90) / 3)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM