首页 > 解决方案 > 嵌套 FOR 循环 - 编码挑战

问题描述

我正在使用STEPIK学习python ,我正面临着这个:

我希望在内部 for 循环的每次迭代中,将predicted_growthlist 的值与 list 的值相加cases,将其保存在某个临时变量中并打印出来。点击链接查看完整挑战。

到目前为止,这是我的代码:

def predict_cases(cases, predicted_growth):
    print()
    result = []
    for i in range(len(cases)):
        for j in range(len(predicted_growth)):
            result = cases[i] + predicted_growth[j]
            print(result, end = " ")
        print()


cases = [12508, 9969, 310595, 57409]
predicted_growth = [100, 200, 300]

predict_cases(cases, predicted_growth)

这是我应该得到的函数的输出:

[12608, 10069, 310695, 57509]
[12808, 10269, 310895, 57709]
[13108, 10569, 311195, 58009]

相反,我得到了这个:

12608 12708 12808 
10069 10169 10269 
310695 310795 310895 
57509 57609 57709 

标签: pythonlistfor-loop

解决方案


您可以使用带有内部列表理解的循环。

def predict_cases(cases, predicted_growth):
    res = [] # this will hold the results

    for growth_rate in predicted_growth: # outer loop to iterate the growth rate
        prev = res[-1] if res else cases # get the previously computed result, if there is no such result get initial cases (`cases`) as previously computed result
        res.append([growth_rate + i for i in prev]) # list comprehension to add the current growth rate(`growth_rate`) to the previous cases

    for result in res: # iterate through `res` list
        print(result) # print the result

cases = [12508, 9969, 310595, 57409]
predicted_growths = [100, 200, 300]
predict_cases(cases, predicted_growths)

输出

[12608, 10069, 310695, 57509]
[12808, 10269, 310895, 57709]
[13108, 10569, 311195, 58009]

推荐阅读