2012-10-03 97 views
9

我的程序看起來像的Python:AttributeError的: 'NoneType' 對象有沒有屬性 '追加'

# global 
item_to_bucket_list_map = {} 

def fill_item_bucket_map(items, buckets): 
    global item_to_bucket_list_map 

    for i in range(1, items + 1): 
     j = 1 
     while i * j <= buckets: 
      if j == 1: 
       item_to_bucket_list_map[i] = [j] 
      else: 
       item_to_bucket_list_map[i] = (item_to_bucket_list_map.get(i)).append(j) 
      j += 1 
     print "Item=%s, bucket=%s" % (i, item_to_bucket_list_map.get(i)) 


if __name__ == "__main__": 
    buckets = 100 
    items = 100 
    fill_item_bucket_map(items, buckets) 

當我運行它,它拋出我

AttributeError: 'NoneType' object has no attribute 'append'

不知道爲什麼這會發生?當我已經在每個j

+0

[Python TkInter - AttributeError:'NoneType'object has no attribute'get']的可能重複(http://stackoverflow.com/questions/1101750/python-tkinter-attributeerror-nonetype-object-has- no-attribute-get) – UpAndAdam

回答

25

其實你存儲None這裏開始創建列表: append()改變的地方名單,返回None

item_to_bucket_list_map[i] = (item_to_bucket_list_map.get(i)).append(j) 

例如:

In [42]: lis = [1,2,3] 

In [43]: print lis.append(4) 
None 

In [44]: lis 
Out[44]: [1, 2, 3, 4] 
+0

這就是抓住,謝謝你選擇這個! – daydreamer

+0

@DSM剛剛檢查過,'None'不是由於get()'而來的,'''存在於字典中,但它的值是'None'。 –

+0

@AshwiniChaudhary:你是對的 - 不知何故,我錯過了它會*多次循環。 – DSM

2
[...] 
for i in range(1, items + 1): 
    j = 1 
    while i * j <= buckets: 
     if j == 1: 
      mylist = [] 
     else: 
      mylist = item_to_bucket_list_map.get(i) 
     mylist.append(j) 
     item_to_bucket_list_map[i] = mylist 
     j += 1 
    print "Item=%s, bucket=%s" % (i, item_to_bucket_list_map.get(i)) 

然而,while循環可以簡化爲

for j in range(1, buckets/i + 1): # + 1 due to the <= 
     if j == 1: 
      mylist = [] 
     else: 
      mylist = item_to_bucket_list_map.get(i) 
     mylist.append(j) 
     item_to_bucket_list_map[i] = mylist 
相關問題