相关疑难解决方法(0)

Python:默认使用Dictionary get方法返回空列表返回None!

在python中我想建立一个使用字典get方法的数组字典,默认情况下提供一个空列表然后填充信息,例如:

dict = {}
for i in range( 0, 10 ):
    for j in range( 0, 100 ):
        dict[i] = dict.get( i, [] ).append( j )
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试上面的代码时,我没有例外,但我的列表最终如下:

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

列表有一个append方法,所以我将我的测试简化为以下内容:

dict = {}
for i in range( 0, 10 ):
    dict[i] = dict.get( i, [] ).append( i )
Run Code Online (Sandbox Code Playgroud)

输出如下:

{0:无,1:无,2:无,3:无,4:无,5:无,6:无,7:无,8:无,9:无}

所以我的问题是为什么dict.get(i,[])默认返回None而不是[]?做dict.get(i,list())有同样的问题,所以我有点难过.

python dictionary list

15
推荐指数
3
解决办法
1万
查看次数

标签 统计

dictionary ×1

list ×1

python ×1