我一直在Python中編寫基於文本的RPG代碼時遇到了麻煩。該RPG爲每個位置使用一個類,並且可以掃描遊戲目錄中的地圖並將其添加到大型3D列表中。這個3D列表中的每個元素都是一個列表本身,包含4個值:座標,名稱,簡短描述和地圖的原始數據。座標未正確分配(Python 3.3)
但是,當我使用該函數更新此映射時,儘管看起來運行正常,但在打印列表元素時卻沒有顯示預期值。
我在我的/ maps文件夾的子目錄中有4個測試map.txt文件,每個文件都有三次檢查座標的準確性。
我的問題減少到代碼如下:
# Imports:
import os
import sys
from random import randint
# Definitions
def create_maps_list():
"""Creates a blank list of 100*100*100 zeros."""
x_list, y_list, z_list, attr_list = [], [], [], []
for _ in range(4):
attr_list.append(0)
for _ in range(100):
z_list.append(attr_list)
for _ in range(100):
y_list.append(z_list)
for _ in range(100):
x_list.append(y_list)
global maps_list
maps_list = x_list
def update_maps_list(maps_list):
"""Updates maplist by scanning the maps dir."""
listdirs = os.listdir(os.getcwd() + "\maps") # List folder names in /maps
for mapdir in listdirs:
mapfile = open("maps/{0}/map.txt".format(mapdir)) # Open map.txt
linelist = list(mapfile)
desc = open("maps/{0}/description.txt".format(mapdir)).read()
mapdata = linelist[2:]
name = linelist[1]
coordsline = linelist[0]
coords = []
for num in coordsline.split():
coords.append(int(num))
x = coords[0]
y = coords[1]
z = coords[2]
print("Name: ", name, "Assigned to coords: ", coords, "\n")
maps_list[x][y][z] = [coords, name, desc, mapdata]
return maps_list
# Assignments:
maps_list = []
list_data = []
# Execution
create_maps_list()
maps_list = update_maps_list(maps_list)
# Output
print()
print("Expected output: [0, 0, 0] Initial Building.")
print(maps_list[0][0][0][0], maps_list[0][0][0][1])
實際輸出如下:
Name: East Building
Assigned to coords: [1, 0, 0]
Name: Heaven!
Assigned to coords: [0, 0, 1]
Name: Initial Building
Assigned to coords: [0, 0, 0]
Name: North Building
Assigned to coords: [0, 1, 0]
Expected output: [0, 0, 0] Initial Building.
[0, 1, 0] North Building
[Finished in 0.3s]
任何援助將不勝感激(包括不直接相關的問題 - 我有一個偷偷摸摸的懷疑,以這種方式存儲座標不是做事情的最佳方式!)
看到這個問題:http://stackoverflow.com/questions/1959744/python-list-problem – happydave