簡體   English   中英

Python __getitem__錯誤

[英]Python __getitem__ error

我有一個快速的問題,這行代碼

row[time] == numbers[num_time]:

給我錯誤:

int has no attribute __getitem__

經過一些研究,我發現當您嘗試在一個int上調用一個列表號時,會發生此錯誤。 在這種情況下,我要發送3個數字的列表,然后想遞歸(我們不允許在第二個數字列表上使用循環:(),看看第二個列表中的任何元素是否在第一個列表中如果是,則將完成某些操作,但如果未完成,則該功能應繼續執行行列表中的下一個操作,執行相同的操作,直到行為空。

def row_find(row,numbers,time,num_time):
    if numbers==[]:
         return row_find(row[time+1],numbers,time+1,num_time=0)
    if row== []:
         return row

    else:
        if  row[time]== numbers[num_time]:
            num_time=0
            return row,row_find(row[time+1],numbers,time+1,num_time)
        else:
            return row,row_find(row[time],numbers[num_time+1],time,num_time)


lst=[5,2,9]
num_lst=[5, 10, 23, 31, 44]
row_find(lst,num_lst,0,0)

這里:

row_find(row[time],numbers[num_time+1],time,num_time)

您正在使用numbers[num_time+1] ,而不是列表。

我認為這應該可以解決問題:

def row_find(row,numbers,time,num_time):
    if numbers==[]: # If numbers list is empty, it make no sense to contiue
         return False
    if row== []: # If numbers list is empty, it make no sense to contiue
         return False

    if  row[time]== numbers[num_time]: #Already found an element that is in both lists
        print("found -> " + str(time) + " " + str(num_time))
        return True
    else:
        if num_time < len(numbers)-1: # If remaining elements in numbers
            if row_find(row,numbers,time,num_time+1): # Check next one
                return True
            else: # I
                if time < len(row)-1: # If remaining element in row
                    return row_find(row,numbers,time+1,0) # check numbers from beginning with next row
                else:
                    return False # If not, no elements in both lists


lst=[8,2,9]
num_lst=[9, 10, 88, 31, 55]
row_find(lst,num_lst,0,0)
# found -> 2 0

檢查您要發送的numbers ,可能是您發送的不是列表。 您得到的錯誤是Python告訴您要在錯誤的對象上使用函數的方式, attribute __getitem__正在到達諸如這些numbers[1]的列表numbers的索引。

這里:

return row,row_find(row[time],numbers[num_time+1],time,num_time)

您傳遞一個整數作為row_findnumbers參數。 您必須通過清單。 您要切片嗎?

你想做

row_find(row[time],numbers[1:],time,num_time)

其中[1:]返回從第二個元素開始的列表。

您還可以使用Python布爾值評估。 如果序列為空,則將其評估為False,因此代替

if numbers==[]:

你可以做:

if not numbers:

您需要做一些事情:

首先,檢查您的參數(數字)實際上是一個列表。 將此添加到您的函數的頂部:

if not isinstance(numbers, collections.Iterable):
    # error! numbers is meant to be a list. report on this error somehow

並且,稍后在您的代碼中:

對於num_lst=[5, 10, 23, 31, 44]num_lst[0] = 5num_list[0++] = 10 如果“數字”為10, numbers[num_time]是什么意思? (即10[num_time] -這是什么意思?)。

而不是將numbers[num_time+1]作為參數傳遞回您的函數,而是使用切片。

暫無
暫無

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

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