python中能否将字典当做值赋给列表呢?
我在对代码做了一个简单的演示,但是为什么不行呢?还是说python就不能列表套字典,只能是字典套列表?
>>> a=[]
>>> b=0
>>> a[b]={'key':'vi'}
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
a[b]={'key':'vi'}
IndexError: list assignment index out of range
>>>
阿神2017-04-18 10:28:45
This problem has nothing to do with list nesting. Normal assignment will also cause your error.
The correct approach is to use the append method of the array.
大家讲道理2017-04-18 10:28:45
a = []
means this is an empty list. There are no elements present.
Python can assign dictionary values to list elements.
黄舟2017-04-18 10:28:45
a is an empty list. Your access to a[0] is obviously out of bounds.
list assignment index out of range means that your access to array index is out of bounds.
PHP中文网2017-04-18 10:28:45
List data type characteristics:
1. Each element of List can be any data type of Python (Boolean, Number, String, List, Dict, Set...)
2. List cannot be accessed out of bounds, it still cannot be accessed and does not exist List element
// 创建一个空List,并将该空List的引用赋值给标识符a
a=[]
// 赋值0给标识符b
b=0
// a[b]此时的含义是,访问List a的第0个元素,然而此时List a还是空的,也就是a[0]不存在,这叫越界访问。
// 在Python中,不允许越界访问,此时会抛出错误:IndexError: list assignment index out of range
a[b]={'key':'vi'}