切换主题
五、列表List
序列是 Python 中最基本的数据结构,Python 有 6 个序列的内置类型,但最常见的是列表和元组
1、创建列表
python
list1 = ['Google', 'Runoob', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
list4 = ['red', 'green', 'blue', 'yellow', 'white', 'black']
2、获取列表元素
1、索引获取
python
list = ['red', 'green', 'blue', 'yellow', 'white', 'black']
print( list[1] )
print( list[-2] )
print( list[-3] )
python
red
white
yellow
2、截取获取
python
nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]
print(nums[0:4])
python
[10, 20, 30, 40]
3、更新列表
python
list = ['Google', 'Runoob', 1997, 2000]
list[2] = 2001
print ("更新后的第三个元素为 : ", list[2])
list1 = ['Google', 'Runoob', 'Taobao']
list1.append('Baidu')
print ("更新后的列表 : ", list1)
python
第三个元素为 : 1997
更新后的第三个元素为 : 2001
更新后的列表 : ['Google', 'Runoob', 'Taobao', 'Baidu']
4、删除列表元素
python
list = ['Google', 'Runoob', 1997, 2000]
print ("原始列表 : ", list)
del list[2]
print ("删除第三个元素 : ", list)
python
原始列表 : ['Google', 'Runoob', 1997, 2000]
删除第三个元素 : ['Google', 'Runoob', 2000]
5、列表比较
列表比较需要引入 operator 模块的 eq 方法
python
# 导入 operator 模块
import operator
a = [1, 2]
b = [2, 3]
c = [2, 3]
print("operator.eq(a,b): ", operator.eq(a,b))
print("operator.eq(c,b): ", operator.eq(c,b))
6、列表脚本操作符
Python 表达式 | 结果 | 描述 |
---|---|---|
len([1, 2, 3]) | 3 | 长度 |
[1, 2, 3] + [4, 5, 6] | [1, 2, 3, 4, 5, 6] | 组合 |
['Hi!'] * 4 | ['Hi!', 'Hi!', 'Hi!', 'Hi!'] | 重复 |
3 in [1, 2, 3] | True | 元素是否存在于列表中 |
for x in [1, 2, 3] : print(x, end=" ") | 1 2 3 | 迭代 |
7、列表函数
函数名 | 描述 |
---|---|
len(list) | 返回列表元素个数 |
max(list) | 返回列表元素最大值 |
min(list) | 返回列表元素最小值 |
list(seq) | 将元组转换为列表 |
8、列表方法
方法名 | 描述 |
---|---|
list.append(obj) | 在列表末尾添加新的对象 |
list.count(obj) | 统计某个元素在列表中出现的次数 |
list.extend(seq) | 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) |
list.index(obj) | 从列表中找出某个值第一个匹配项的索引位置 |
list.insert(index, obj) | 将对象插入列表 |
list.pop([index=-1\]) | 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 |
list.remove(obj) | 移除列表中某个值的第一个匹配项 |
list.reverse() | 反向列表中元素 |
list.sort( key=None, reverse=False) | 对原列表进行排序 |
list.clear() | 清空列表 |
list.copy() | 复制列表 |