2012-10-03 23 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'

わからない私を投げのように見えていません起こる?私はすでに実際にあなたがここにNoneを格納し、各j

+0

[Python TkInter - AttributeError: 'NoneType'オブジェクトに属性 'get'がありません。](http://stackoverflow.com/questions/1101750/python-tkinter-attributeerror-nonetype-object-has- no-attribute-get) – UpAndAdam

答えて

25

の開始時にリストを作成していた場合: 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がチェックされただけですが、 'なし'は 'get()'によって出てこないので、 'i'は辞書にありますが、値は' 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 
関連する問題