List
List 是 Python 中最常用的数据类型,在此仅对其做简单归纳整理
我们都知道,在 Python 6 种基础数据类型中,String List Tuple 这三种均属于序列类型,而序列通用的操作包括:索引、长度、组合(序列相加)、重复(乘法)、分片、检查成员、遍历、最小值和最大值。
1. 索引
通过索引的方式,我们可以对列表进行访问以及更新操作:
>>> list = ["hello", "python", 2019]
>>> print(list[1])
>>> list[2] = 2020
>>> print(list)
python
['hello', 'python', 2020]
与字符串类似,我们也可以对列表进行切片:
>>> list = ["hello", "python", 2019]
>>> print(list[1:])
>>> print(list[:])
>>> print(list[:-2])
['python', 2019]
['hello', 'python', 2019]
['hello']
2. 列表脚本操作符
(1) 列表长度 len()
>>> list = ["hello", "python", 2019]
>>> print(len(list))
3
(2) 组合 +
>>> list = ["hello", "python", 2019]
>>> sec_list = ["jupyter", "notebook"]
>>> print(list+sec_list)
['hello', 'python', 2019, 'jupyter', 'notebook']
(3) 重复 *
>>> list = ["hello", "python", 2019]
>>> print(list*2)
['hello', 'python', 2019, 'hello', 'python', 2019]
(4) 检查成员 in
>> list = ["hello", "python", 2019]
>>> print("hello" in list)
True
(5) 遍历 for in
>>> list = ["hello", "python", 2019]
>>> for item in list:
>>> print(item, end=" ")
hello python 2019
3. 列表函数、方法
1. 常用函数
(1) len(list) 列表元素个数
(2) max(list) 返回列表元素最大值
(3) min(list) 返回列表元素最小值
(4) list(seq) 将元组转换为列表
2. 方法
添加元素
(1) list.append(obj) 在列表末尾添加新的对象
(2) list.insert(index, obj) 将对象插入列表
(3) list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
删除元素
(1) list.pop([index=-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
(2) list.remove(obj) 移除列表中某个值的第一个匹配项
(3) list.clear() 清空列表
排序
(1) list.sort( key=None, reverse=False) 对原列表进行排序
(2) list.reverse() 反向列表中元素
其他常用方法
(1) list.count(obj) 统计某个元素在列表中出现的次数
(2) list.index(obj) 从列表中找出某个值第一个匹配项的索引位置
(3) list.copy() 复制列表