簡體   English   中英

如何獲得項目索引

[英]How to get index of item

我正在嘗試獲取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,而它應以5-1 = 4返回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 ,這是第一個或多個precicely,第零個元素。 因此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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM