簡體   English   中英

Python的列表索引必須是整數,而不是元組“錯誤

[英]Python 'list indices must be integers, not tuple" error

我正在努力將機器人移動到8 x 8的2d網格室,其中一部分是初始化傳感器,其中包括機器人周圍最近的5個瓦片。

self.sensors = [0 for x in xrange(5)]

在這里,我正在創建一個由5個元素組成的空數組。

但是當我嘗試像這樣設置傳感器的值時:

    if self.heading == 'East':
        self.sensors[0] = self.room[self.x, self.y-1]
        self.sensors[1] = self.room[self.x+1, self.y-1]
        self.sensors[2] = self.room[self.x+1, self.y]
        self.sensors[3] = self.room[self.x+1, self.y+1]
        self.sensors[4] = self.room[self.x, self.y+1]

我得到'列表索引必須是整數而不是元組'的錯誤。

你說self.room是一個“二維網格” - 我認為它是一個列表清單。 在這種情況下,您應該訪問其元素

self.room[self.x][self.y-1]

而不是使用self.x, self.y-1對索引外部列表。

問題來自你的self.room

因為這個:

self.room[self.x, self.y-1]

是相同的:

self.room[(self.x, self.y-1)]

這就是你的tuple錯誤。

有兩種可能性:

  • self.room是一個2D數組,這意味着你可能意味着:

     self.room[self.x][self.y-1] 
  • 你想切片self.room

     self.room[self.x:self.y-1] 

請提供有關self.room更多信息。

self.room[self.x, self.y-1]用元組索引self.room 如果它是一個self.room[self.x][self.y-1]數組,那么你必須使用self.room[self.x][self.y-1]

為什么會出錯? 我沒有通過任何元組!

因為處理[]解析的__getitem__self.room[1, 2]轉換為元組:

class C(object):
    def __getitem__(self, k):
        return k

# Single argument is passed directly.
assert C()[0] == 0

# Multiple indices generate a tuple.
assert C()[0, 1] == (0, 1)

和列表不是為了處理這些論點。

更多示例: https//stackoverflow.com/a/33086813/895245

什么是self.room的類型,我認為房間是一個列表,在這種情況下你必須像這樣分配

if self.heading == 'East':
   self.sensors[0] = [self.x, self.y-1]

或者像這樣

if self.heading == 'East':
    self.room = [self.x, self.y-1]
    self.sensors[0] = self.room

像這樣

>>> a = []
>>> type(a)
<type 'list'>

>>> a[2,3]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: list indices must be integers

>>> a = [2,3]

這是因為列表索引必須是整數,而不是其他任何東西。 在您的情況下,您正在嘗試使用元組。

你的代碼特別奇怪,因為你self.room用元組索引創建self.room

暫無
暫無

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

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