2013-12-22 11 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