首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NoneType:'append‘对象没有’append‘属性

NoneType:'append‘对象没有’append‘属性
EN

Stack Overflow用户
提问于 2012-10-04 03:09:57
回答 2查看 61.2K关注 0票数 11

我的程序看起来像

代码语言:javascript
复制
# 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的开头创建一个列表时

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-10-04 03:11:43

实际上您在这里存储了Noneappend()原地更改列表并返回None

代码语言:javascript
复制
 item_to_bucket_list_map[i] = (item_to_bucket_list_map.get(i)).append(j)

示例:

代码语言:javascript
复制
In [42]: lis = [1,2,3]

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

In [44]: lis
Out[44]: [1, 2, 3, 4]
票数 30
EN

Stack Overflow用户

发布于 2012-10-04 03:15:25

代码语言:javascript
复制
[...]
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循环简化为

代码语言:javascript
复制
    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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12715198

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档