如何获得项目索引

时间:2013-09-23 04:14:44

标签: python python-3.x

我试图在4x4网格中获取二进制整数的左,右,底部和顶部的项目索引。我现在正在做的事情似乎没有获得正确的值索引。

        if self.data[index] == 1:
            self.data[index] = 0
                if self.data.index(self.data[index]) - 1 >= 0:
                    print("Left toggled")
                    if self.data[index - 1] == 1:
                        self.data[index - 1] = 0
                    else:
                        self.data[index - 1] = 1

截至目前,我正在尝试使用010011100100的位数组,如果上面的代码示例中的index = 5返回-1,那么它应该返回4为5-1 = 4。 / p>

我认为我的if语句if self.data.index(self.data[index]) - 1 >= 0:是错误的,但我不确定我想要表达的语法。

1 个答案:

答案 0 :(得分:4)

让我们逐步完成您的代码,看看会发生什么......

#We'll fake these in so the code makes sence...
#self.data must be an array as you can't reassign as you are doing later
self.data = list("010011100100")
index = 5

if self.data[index] == 1:      # Triggered, as self.data[:5] is  "010011"
    self.data[index] = 0       # AHA self.data is now changed to "010010..."!!!
        if self.data.index(self.data[index]) - 1 >= 0:
           #Trimmed

在倒数第二行,您将获得self.data[index]现在为0,因为我们之前更改了该行。

但是,请记住 Array.index() 会返回数组中该项的第一个实例。因此self.data.index(0)返回0的第一个实例,它是第一个或更准确的第零个元素。因此self.data.index(0)给出了00-1就是...... -1

至于你的代码应该是什么,这是一个更难的答案。

我认为您的条件可能只是:

width  = 4 # For a 4x4 grid, defined much earlier.
height = 4 # For a 4x4 grid, defined much earlier.

...

if index%width == 0:
    print "we are on the left edge"
if index%width == width - 1:
    print "we are on the right edge"
if index%height == 0:
    print "we are on the top edge"
if index%height == height - 1:
    print "we are on the bottom edge"