2013-12-22 14 views
0

我目前正在研究一個基於文本的冒險遊戲。這是我的一個編程課程期末作業,我得到了尖端從導師之一來使用模量減少代碼量來實現:綁定列表索引與模數,想做一個循環列表

def viable(self, north_south, east_west): 
    i = north_south.index(self) 
    j = east_west.index(self) 
    if i == 0: 
     south = north_south[len(north_south)-1] 
    else: 
     south = north_south[i-1] 
    if i == len(north_south)-1: 
     north = north_south[0] 
    else: 
     north = north_south[i+1] 
    if j == 0: 
     west = east_west[len(east_west)-1] 
    else: 
     west = east_west[i-1] 
    if j == len(east_west)-1: 
     east = east_west[0] 
    else: 
     east = east_west[j+1] 

    viable = [east, west, north, south] 
    return viable 

如果任何人可以就如何綁定任何建議最後的指數和第一個指數在一起?

回答

0

使用%模塊使你的代碼簡單了很多,是的,因爲它消除了需要測試的邊緣情況:

def viable(self, north_south, east_west): 
    i = north_south.index(self) 
    j = east_west.index(self) 

    south = north_south[(i - 1) % len(north_south)] 
    north = north_south[(i + 1) % len(north_south)] 
    west = east_west[(j - 1) % len(east_west)] 
    east = east_west[(j + 1) % len(east_west)] 

    return east, west, north, south 

換句話說,只需添加或從指數中減去,然後應用長度作爲「纏繞」到另一側的模量。

比方說,你的名單長度是5,那麼% 5爲您提供了各種情況下的輸出:

>>> 5 % 5 # last index + 1 
0 
>>> -1 % 5 # first index - 1 
4 
>>> 3 % 5 # middle + 1 
3 
+0

謝謝要去立即應用此吧:) – August