如何获取项目的索引
问题描述:
我想获取项目的索引到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
位阵列,其在上面的代码示例返回-1,如果index = 5
当它应该返回4为5-1 = 4尝试。
我假设我的if语句if self.data.index(self.data[index]) - 1 >= 0:
是错误的,但我不确定我试图完成的语法。
答
通过您的代码让一步,看看会发生什么......
#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)
给出0
和0-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"
是啊,这是关于多远我想通了。我试图基本上做的是相应地更改第四个索引,而不是对索引内的值进行数学运算。 – Bob
@BobDunakey Forth索引,你的意思是第四? – 2013-09-23 04:32:00
@LegoStromtrooper是错字。 – Bob