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'对象没有属性'append'
Not sure why this would happen? When I am already creating a list at start of each j
不知道为什么会这样?当我已经在每个j的开头创建一个列表时
2 个解决方案
#1
26
Actually you stored None
here: 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]
#2
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))
The while
loop, 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
#1
26
Actually you stored None
here: 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]
#2
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))
The while
loop, 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