带模数的绑定列表索引,想要制作一个循环列表

时间:2013-12-22 18:57:22

标签: python python-3.3 modulus

我目前正致力于基于文本的冒险游戏。这是我编程课程的最后一项任务,我从其中一位教师那里获得了使用模数来减少完成此任务的代码量的提示:

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

如果有人可以就如何将最后一个索引和第一个索引绑定在一起提出任何建议吗?

1 个答案:

答案 0 :(得分: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