所以我有一個數據文件,我想找到兩件事:我給出的坐標是在區域內部還是外部,如果正確則返回將“1”的每個坐標放在其自己列表中的每一行中。這應該將其返回到字典中。該文件有以下內容:1 1 0 1 0 10 0 1 1 1 01 1 1 1 1 01 0 0 0 0 10 0 1 1 0 11 0 0 0 0 1我已將上述內容放入一個列表中,每個列表都包含代碼:lines = []with open('area.dat', 'r') as a: for line in a: line = line.strip() if not line: continue lines.append(list(map(int, line.split()))) data.extend(map(int, line.split()))print(lines)我嘗試通過代碼獲取坐標以及它是在區域之外還是在區域之內(對于 x 和 y)區域是列表的列表x = int(input('enter x: '))y = int(input('enter y: '))def cords(x, y, area): if x > 6 or y > 6: print('Outside Area') return(False) else: print('Inside Area') return(True)我想獲取列表“區域”內的坐標 x 和 y 并返回它是否在其中。因此,例如,如果我輸入 cords(0,4,area) 它將返回“True”,如果我輸入 cords(3,7,area) 它將返回“False”。之后我想將它們按每行以 1 為一組放在一起。例如,第 1 行和第 2 行將給出:{1: [(0,4), (0,5)], 2: [(1,0), (1,1)]}感謝所有幫助。
1 回答

慕娘9325324
TA貢獻1783條經驗 獲得超4個贊
對于第一部分,您有兩個選擇:
def cords(x, y):
return x >= 0 and x < 6 and y >= 0 and y < 6
第一個選項對于 6x6 的區域大小是靜態的,請注意,數組索引從 0 開始,因此 6 已經超出范圍。
def cords(x, y, area):
return x >= 0 and x < len(area) and y >= 0 and y < len(area[0])
第二個選項動態檢查坐標是否在給定嵌套列表的范圍內。您可能需要根據 x 和 y 是否與行和列相關來調整它,反之亦然。
現在,對于第二部分,您正在創建一個包含冗余信息的字典,因為索引(示例中的 1 和 2)直接與第一個軸(示例中的 0 和 1)相關,您可能需要重新考慮您實際的內容想要在這里實現。
d = {}
for i,row in enumerate(lines):
n = []
for j,v in enumerate(row):
if v == 1:
n.append([i,j])
d[i+1] = n
添加回答
舉報
0/150
提交
取消