為基本問題道歉,我是 Python 新手,正在努力尋找答案。
如何為loaded_route串列中的每個專案執行以下if 陳述句?
即檢查第一個loaded_route值,更新位置,然后檢查下一個值,更新位置等。
我當前的 for 回圈比較整個串列,而不是單個值。謝謝!
location = [1,1]
loaded_route = ['right', 'left']
route_coords = []
for route in loaded_route:
if route == 'right':
location[0] = (location[0] 1)
route_coords.append(location)
elif route == 'left':
location[0] = (location[0] - 1)
route_coords.append(location)
elif route == 'up':
location[1] = (location[1] - 1)
route_coords.append(location)
elif route == 'down':
location[1] = (location[1] 1)
else:
print('failed to read loaded_route')
uj5u.com熱心網友回復:
location是串列型別,而串列在 Python 中是“可變的”。這意味著每次添加location到 時route_coords,您只是插入對 的參考location,允許不斷更改。
相反,您希望將當前位置值復制到route_coords.
location = [1,1]
loaded_route = ['right', 'left']
route_coords = []
for route in loaded_route:
if route == 'right':
location[0] = (location[0] 1)
route_coords.append(location[:])
elif route == 'left':
location[0] = (location[0] - 1)
route_coords.append(location[:])
elif route == 'up':
location[1] = (location[1] - 1)
route_coords.append(location[:])
elif route == 'down':
location[1] = (location[1] 1)
route_coords.append(location[:])
else:
print('failed to read loaded_route')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/510382.html
