【问题标题】:Python: "'Nonetype' is not iteratable" without any iterationPython:没有任何迭代的“'Nonetype'不可迭代”
【发布时间】:2016-04-01 13:37:28
【问题描述】:

我正在编写一个程序来通过线性探测形成不同大小的哈希表。在用于线性探测的 ADT 中,我有一个函数 def insert ( ),它是从我的主脚本中从以下函数调用的:

def insertHashTable(  loadNum, hashTable  ):
    i = 0
    while i < ((loadNum*size)-1):
        hashTable.insert(data[i],data[i])
        i = i + 1
    return hashTable 

错误本身来自这个从insertHashTable()调用的函数

def insert( self, key, value ):
    ( found, slot ) = self._findSlot( key ) #ERROR HERE
    if not found :
        self._table[slot] = _MapEntry( key, value ) #custom datatype
        self._count += 1
    return not found

我在这段代码的第二行得到了非类型错误。最后,_findSlot( ) 如下:

def _findSlot( self, key ):        
    startLoc = self._hash1( key )

    self.slotsAccessed += 1
    if self._table.__getitem__( startLoc ) == None:
        return (False, startLoc)

    else:
        c = 0
        while (c+startLoc) < (self._size -1):
            if self._table[startLoc+c] == None:
                return (False, startLoc+c) 
            elif self._table.__getitem__( startLoc ).key == key:
                return (True, startLoc+c) 
            c = c + 1
            self.slotsAccessed += c

我不确定为什么 insertHashTable() 函数会出现这样的错误,因为密钥没有发生迭代。

但是我知道我的哈希表在表初始化时的每个插槽中都有“无”,也许有一些问题?

【问题讨论】:

  • (c+startLoc)

标签: python iteration runtime-error hashtable nonetype


【解决方案1】:

您的_findSlot(self, key) 函数可以在没有返回语句的情况下完成。 (具体来说,如果您的while 条件变为假并且循环结束,就会发生这种情况。)在这种情况下,函数将返回None。如果您尝试将值 None 分配给 (found, slot),则会收到错误 Nonetype is not iterable

你可能需要弄清楚你的函数在当前返回None的情况下应该返回什么。

【讨论】:

    猜你喜欢
    • 2013-12-01
    • 1970-01-01
    • 2019-10-23
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 2020-05-06
    相关资源
    最近更新 更多