python - 嵌套 FOR 循环 - 编码挑战
问题描述
我正在使用STEPIK学习python ,我正面临着这个:
我希望在内部 for 循环的每次迭代中,将predicted_growth
list 的值与 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
解决方案
您可以使用带有内部列表理解的循环。
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]
推荐阅读
- java - 语法错误,插入“{”以完成 EnumBody(在类结束时)
- rest - 退出restful服务只是在本地销毁令牌?
- bash - 如何将詹金斯声明性管道中的环境值返回到文件?
- java - 如何使用 getKeyStroke(String s) 方法?
- swift - 在 Swift 中,如何在已经使用 One 的函数中使用 Completion Handler?
- python - Pandas:统计 4 天内 2 次访问的发生次数
- python - 在python中访问with关键字之外的变量
- java - 如何在 Scala 中实现 Java 接口(用于 Kafka)?
- javascript - 如何仅将多维数组的一部分展平一层?
- html - 如何分隔两个多列`那些连接在一起的?