Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

list - Python : AttributeError: 'NoneType' object has no attribute 'append'

My program looks like

# 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)

When I run this, it throws me

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

Not sure why this would happen? When I am already creating a list at start of each j

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Actually you stored None here: append() changes the list in place and returns None

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

example:

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.7k users

...