(一)比较几种数据结构
→ 使用方括号 [ ] 创建列表
→ 使用圆括号 ()创建字典
→ 使用花括号 { } 创建字典
其中,每种类型中,都可以通过方括号 [ ] 对单个元素进行访问
→ 对于列表和元组,方括号里是整型的偏移量,即索引
→ 对于字典,方括号里是 键
→ 最后均返回元素的值
(二)建立大型数据结构
① 将这些内置的数据结构自由地组合成更大、更复杂的结构
② 创建自定义数据结构的过程中,唯一的限制来自于这些内置数据类型本身
建立3个不同的列表
alist = [1,2,3]
blist = ['Hello', 'python']
clist = [True, False]
嵌套列表 / 元组
list_of_list = [[1,2,3], ['Hello', 'python'], [True, False]]
tuple_of_list = ([1,2,3], ['Hello', 'python'], [True, False])
列表嵌套,元素可以进行复制修改
>>> list_of_list[1][1]
'python'
>>> list_of_list[1][1] = 'world'
>>> list_of_list[1][1]
'world'
元组嵌套,可以对其中的列表进行修改,不能对元组本身进行修改
>>> tuple_of_list = ([1,2,3], ['Hello', 'python'], [True, False])
>>> tuple_of_list[1][1]
'python'
① 对列表元素的子元素进行修改
>>> tuple_of_list[1][1] = 'world'
>>> tuple_of_list[1][1]
'world'
② 尝试对元组本身元素进行修改,出现异常! 灵感:大胆猜测!可以用元组来定义一个游戏角色的属性,对于每种属性可以用可变数据类型来定义。
>>> tuple_of_list[1]
['Hello', 'world']
>>> tuple_of_list[1] = 'abc'
Traceback (most recent call last):
File "<pyshell#58>", line 1, in <module>
tuple_of_list[1] = 'abc'
TypeError: 'tuple' object does not support item assignment
嵌套字典
>>> dict_of_lists = {'num':[1, 2, 3], 'word':['hello', 'python'], 'bool':[True, False]}
>>> dict_of_lists['word']
['hello', 'python']
>>> dict_of_lists['word'][1]
'python'
>>> dict_of_lists['word'][1] = 'world'
>>> dict_of_lists['word']
['hello', 'world']
字典的元素(值value)可以是任意类型,甚至也可以是字典
字典的键 (key)可以是任意不可变类型,即可哈希
例如用元组来作为坐标,索引元素
来源:CSDN
作者:san_seven
链接:https://blog.csdn.net/qq_41856926/article/details/104342821