对于以下程序,在addEntry(self,dictKey,dictVal)函数中,我不明白为什么以下代码行不会生成索引错误:
if hashBucket[i][0] == dictKey
self.buckets
最初是一个空列表列表:
self.buckets = [[],[]...[]]
当第一次执行addEntry时,hashBucket
只是一个空列表,所以我希望hashBucket[i][0]
会产生索引错误,但程序实际上有效,为什么?非常感谢你的帮助。
这是程序
class intDict(object):
"""A dictionary with integer keys"""
def __init__(self, numBuckets):
"""Create an empty dictionary"""
self.buckets = []
self.numBuckets = numBuckets
for i in range(numBuckets):
self.buckets.append([])
def addEntry(self, dictKey, dictVal):
"""Assumes dictKey an int. Adds an entry"""
hashBucket = self.buckets[dictKey%self.numBuckets]
for i in range(len(hashBucket)):
if hashBucket[i][0] == dictKey:
hashBucket[i] = (dictKey, dictVal)
return
hashBucket.append((dictKey, dictVal))
def getValue(self, dictKey):
"""Assumes dictKey an int. Returns entry associated with the key dictKey"""
hashBucket = self.buckets[dictKey%self.numBumBuckets]
for e in hashBucket:
if e[0] == dictKay:
return e[1]
return None
def __str__(self):
result = '{'
for b in self.buckets:
for e in b:
result = result + str(e[0]) + ":" + str(e[1]) + ','
return result[:-1] + '}' # result[:-1] omits the last coma
答案 0 :(得分:2)
由于hashBucket
一开始是一个空列表,for i in range(len(hashBucket)):
基本上是for i in range(0):
,这意味着它在第一次调用{{1}时永远不会到达条件if hashBucket[i][0] == dictKey
}。
答案 1 :(得分:2)
当你试图循环一个空列表时,什么都不会发生,启动一个python interpeter并尝试这个
gene_name V1
1: g1 3.720619
2: g2 35.727923
3: g3 -3.949385
4: g4 -18.253456
5: g5 5.970879
---
496: g496 -20.979669
497: g497 63.880925
498: g498 16.498587
499: g499 -17.417110
500: g500 45.169608
没有任何内容被打印出来,所以如果>>> for i in range(len([])):
... print(i)
...
>>>
为空,那么for循环中的所有内容都将永远不会被执行
hashBucket
答案 2 :(得分:0)
第一次执行时hashBucket为空。范围是空的。所以这个for循环没有做任何事情。 'for i in range(len(hashBucket)):' 我认为。 是吗?