Python:AttributeError:'NoneType'对象没有属性'append'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12715198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:40:55  来源:igfitidea点击:

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

pythonlist

提问by daydreamer

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'

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

不知道为什么会发生这种情况?当我已经在每个开始时创建列表时j

采纳答案by Ashwini Chaudhary

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

实际上您存储None在这里: append()更改列表并返回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]

回答by glglgl

[...]
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))

The whileloop, however, can be simplified to

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