python中列表内能否套字典?
迷茫
迷茫 2017-04-18 10:26:45
0
5
888

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
>>> 

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(5)
阿神

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.

大家讲道理

a = []
means this is an empty list. There are no elements present.
Python can assign dictionary values ​​to list elements.

伊谢尔伦
a.append({'key':'vi'})
黄舟

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.

Ty80

Python knowledge points:

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

Code analysis:

// 创建一个空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'}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template