-2
我想創建一個循環。這個循環應該做一個迭代。我唯一需要的是最後一次迭代。我想知道是否可以爲此創建一個動態堆棧,這樣我就不會事先定義一個使用內存的矩陣。我怎麼能這樣做?Python循環和動態堆棧
我想創建一個循環。這個循環應該做一個迭代。我唯一需要的是最後一次迭代。我想知道是否可以爲此創建一個動態堆棧,這樣我就不會事先定義一個使用內存的矩陣。我怎麼能這樣做?Python循環和動態堆棧
我想你想要最後一次迭代的結果?
如果是的話,這應該做的伎倆:
#!/usr/bin/env python3
j=0
for i in range(13):
# with each iteration j grows by 37
j+=37
# note: Accessing values from last iterations like below can be hard to accomplish
# and may require more helper variables or finally a list.
print("step " + str(i) + ": \tj grew from " + str(j-37) + " to " + str(j) + ".")
# At this point j got overwritten 13 times and holds the value of 13*37.
print("Finally j holds the value " + str(j) + ".")
如果我把你錯了,你就真的只想做最後的「迭代」你基本上不重複。你會消除環路,並將舊循環之內的高度複雜的計算之前設置我的迭代的最後一個值:
#!/usr/bin/env python3
j=0
i=12 # the last value of range(13)
# the old loop:
j+=37
print("'step' " + str(i) + ": \tj grew from " + str(j-37) + " to " + str(j) + ".")
# end of the old loop
# At this point j got overwritten one time and holds the value of 1*37.
print("finally j holds the value " + str(j) + ".")
第二部分是可能微不足道,只是爲了完整起見。 我希望這能回答你的問題。 請在下一次您詢問Q & A板時考慮代碼示例。
也許你可以提出一些你試過的代碼,這會讓這個更清晰? – pvg
爲什麼你需要一個堆棧?只需使用一個變量並在每次迭代中覆蓋它。最後它會存儲最後一次迭代的值。 – melpomene
我們需要在這裏看到一些代碼。也許「反向」功能就是你正在尋找的功能,但是如果沒有看到任何代碼就不可能分辨出來。 –