【发布时间】:2020-03-28 04:44:32
【问题描述】:
我有一些丑陋的代码可以做我想做的事情,即对列表中的每个值执行一个函数“x // 3 - 2”,直到该值为 0(并每次存储结果以相加稍后),但我想修改它以提供数百个列表值,而不仅仅是这三个。
fuellist = []
modules = [14, 1969, 100756]
def getfuel(lst):
newlist = [x // 3 - 2 for x in lst]
for x in newlist:
if x < 0:
newlist.remove(x)
return newlist
list1 = getfuel(modules)
list2 = getfuel(list1)
list3 = getfuel(list2)
list4 = getfuel(list3)
list5 = getfuel(list4)
list6 = getfuel(list5)
list7 = getfuel(list6)
list8 = getfuel(list7)
list9 = getfuel(list8)
list10 = getfuel(list9)
total = list1 + list2 + list3 + list4 + list5 + list6 + list7 + list8 + list9 + list10
print(sum(total))
输出是/应该是这个列表:51314
我不记得最好的方法了。我试过使用while循环,但它陷入了某种无限循环。我不确定“递归”是否适合我正在寻找的东西,我希望我能更好地解释它。感谢您的帮助。
【问题讨论】:
-
“我尝试过使用 while 循环,但它陷入了某种无限循环。”:所以这更像是一个实际的实际问题,但您没有显示该代码。可能,这就是您想要回答的代码(和问题)。
-
关于改进代码的建议,你可能会更好codereview.stackexchange.com。
标签: python list function recursion