第三章:列表简介
1.列表的定义和命名
(1)定义
用方括号定义一个列表:[ ]
用逗号分隔其中的元素:,
(2)命名
最好使用表示复数的名称来命名列表:例如:letters,names等

2.访问和使用列表元素
使用索引进行访问。
需要注意的是:
1.索引从0开始而非1;
2.负数索引表示倒着数的第n个。

3.修改、添加和删除元素
(1)修改元素:直接赋值改变

(2)添加元素
1.在末端添加:使用append()方法

2.在指定位置添加:使用
insert()方法

3.删除元素
1.使用del
del list[n]:删除list列表中索引为n的元素

2.使用pop()方法
list.pop():弹出list列表的最后一个元素
list.pop(n):弹出list列表中索引为n的元素
*:需要注意的是:pop()方法有返回值,即返回被弹出的元素。

3.使用remove()方法
list.remove('out'):弹出list列表中值为‘out’的第一个元素
*:需要注意的是:remove()方法没有返回值,
且只删除对应值的第一个元素,若有重复值,则需循环进行删除。

4.组织列表
(1)永久性排序:使用sort()方法
list.sort():将list列表按照字母升序排序
*:若需要逆序,则给sort()方法添加一个参数:reverse=True
即:list.sort(reverse=True)

(2)临时性排序:使用sorted()方法
调用sorted()方法,不影响列表本身

sorted()方法的调用与sort()不一样,注意看示例
(3)反转列表:使用reverse()方法
list.reverse():将list列表的顺序反转。
*:影响列表本身,但再次调用即恢复原列表

(4)确定列表长度:使用len()
len(list):返回list列表的长度值。

网友评论