簡體   English   中英

如何在python中操作列表

[英]how to manipulate a list in python

我只是想問你一個關於用Python構建迷宮的運動知識。 我們從一個已知的(x,y)點和n * n圖開始。 在每次遞歸中,我們應該為每對夫婦(x,y)制作一個neighbouring_list,其中將包含該點的最近元素。 到目前為止,我已經編寫了這段顯示正確結果的代碼,但是我無法保存和操作從相鄰列表中選擇的新x和y的排他性。 它們的執行方式類似於(8,8),我無法寫出x = 8和y = 8。 先感謝您!

if(x and y == 0):
    neighbouring_list = [((x + 1), y), (x, (y + 1))]
elif (x == (n - 1) and y == 0):
    neighbouring_list = [((x - 1), y), (x, (y + 1))]
elif (y == 0):
    neighbouring_list = [((x + 1), y), ((x - 1), y), (x, (y + 1))]
elif (y == (n - 1) and x == 0):
    neighbouring_list = [(x, (y - 1)), ((x + 1), y)]
elif (x == 0):
    neighbouring_list = [(x, (y + 1)), (x, (y - 1)), ((x + 1), y)]
elif (x == (n - 1) and y == (n - 1)):
    neighbouring_list = [(x, (y - 1)), ((x - 1), y)]
elif (x == (n - 1)):
    neighbouring_list = [((x - 1), y), (x, (y + 1)), (x, (y - 1))]
elif (y == (n - 1)):
    neighbouring_list = [(x, (y - 1)), ((x - 1), y), ((x + 1), y)]
else:
    neighbouring_list = [((x - 1), y), ((x + 1), y), (x, (y + 1)), (x, (y -         1))]

這是您的代碼的簡單得多的版本:

nlist = []
if x < n:
    nlist.append((x+1,y))
if y < n:
    nlist.append((x,y+1))
if x > 0:
    nlist.append((x-1,y))
if y > 0:
    nlist.append((x,y-1))

這應該更容易管理。

要將元組(xin,yin)解壓縮為代碼的x,y,只需執行以下操作:

x, y = (xin, yin)

或者如果元組綁定到變量,例如坐標:

x, y = coordinates

這稱為元組拆包。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM