#容器是一种存储大量数据的一种数据类型。
#python中提供了四种容器,分别是:list(列表)、set(集合)、tuple(元组)、dict (字典)
一、list
list是一种线性结构的存储空间。列表是Python中最具有灵活性的有序集合对象类型,与字符串不同的是,列表可以包含任何种类的对象:数字、字符串、甚至是列表。同样,与字符串不同的是,列表是可变对象,他们都支持在原处修改的操作,同样列表的长度是可变的。
1、列表的创建方式
<1>直接指定元素
>>> [1,2,3,4,5]
>>> l = [1,2,3,4,5]
<2>指定长度但不指定元素,相当于创建一个长度为n但不存任何数据对象地址的空列表。
>>> l = [None] * 10
>>> l
[None, None, None, None, None, None, None, None, None, None]
<3>通过list函数将其他的数据转换为列表,这些数据必须是可迭代的,可迭代的就是可以被for循环操作。
>>> list() # 得到一个长度为0的列表
[]
>>> l = list("abcd")
>>> l
['a', 'b', 'c', 'd']
>>> l[0]
'a'
>>> l[-1]
'd'
>>> l = list(range(0,5))
>>> l
[0, 1, 2, 3, 4]
>>> l =list(1234)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
2、列表的特有操作
<1>修改元素
>>> l
[0, 1, 2, 3, 4]
>>> l[0]=5
>>> l
[5, 1, 2, 3, 4]
<2>删除操作
>>> l
[1, 2, 3, 666, 888, 999, 8, 9]
>>> del l[3]
>>> l
[1, 2, 3, 888, 999, 8, 9]
>>> del l[-3]
>>> l
[1, 2, 3, 888, 8, 9]
>>> del l # 删除列表对象 连着变量也一同删除
>>> l
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'l' is not defined
3、常见的使用方法
<1>append():在列表的表尾添加一个元素对象
>>> l = [1,2,3]
>>> l.append(4)
>>> l
[1, 2, 3, 4]
>>> l1 = [1,2,3,4]
>>> l2 = [5,6,7,8]
>>> l1.append(l2)
>>> l1
[1, 2, 3, 4, [5, 6, 7, 8]]
>>> l1.append("abc")
>>> l1
[1, 2, 3, 4, [5, 6, 7, 8], 'abc']
<2>clear():清空列表,不代表删除列表对象
>>> l.clear()
>>> l
[]
<3>copy():复制一份新的列表对象,与原列表内容一致,将新列表的地址返回
>>> l1 = [1,2,3,4]
>>> l2 = l1
>>> l2[0] = 5
>>> l1
[5, 2, 3, 4]
>>> l2 = l1.copy()
>>> l1
[5, 2, 3, 4]
>>> l2
[5, 2, 3, 4]
>>> l2[0]=10
>>