Python 中可以通过组合一些值得到多种复合数据类型。其中最常用的列表,可以通过方括号括起、逗号分隔的一组值得到。一个列表可以包含不同类型的元素,但通常使用时各个元素类型相同 6.常见列表操作函数

1.列表的定义

>>> list = [1,2,3,4,5]
>>> type(list)
<class 'list'>

>>> list
[1,2,3,4,5]

2.访问列表某个元素

>>> list = [1,2,3,4]
>>> list[0]
1

>>> list[3]
4

>>> list[-1]
4

>>> list[-2]
3

3.列表切片操作

注意:在使用切片时,要注意左开右合,就是左边是闭区间,右边是开区间

>>> list = [1,2,3,4,5,6,7,8,9,10]
>>> list[0:5]
[1, 2, 3, 4, 5] #返回一个列表

>>> list[0:-1]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> list[0:-3]
[1, 2, 3, 4, 5, 6, 7]

>>> list[3:]
[4, 5, 6, 7, 8, 9, 10]

>>> list[3:-1]
[4, 5, 6, 7, 8, 9]

>>> list[:4]
[1, 2, 3, 4]

>>> list[:-1]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> list[-1:4]
[]

复杂切片操作

alist = [1, 2, 3, 4, 5, 6, 7, 8, 9]

print(alist[::])  # 返回包含原有列表所以元素的新元素
print(alist[::-1])  # 将列表元素反转后返回
print(alist[::2])  # 隔一个取一个,获取偶数位置元素
print(alist[1::2])  # 隔一个取一个,获取奇数位置元素
print(alist[3:6])  # 指定切片起始位置和结束位置
print(alist[0:100])  # 切片结束位置大于列表长度,从列表尾部截断
print(alist[100:])  # 切片的起始位置大于列表长度时,返回空列表

alist[len(alist):] = [10]  # 在列表尾部增加元素
alist[:0] = [-1,0]  # 在列表头部插入元素
alist[5:5] = [5]  # 在列表中间插入元素
alist[:3] = [0, 0, 0]  # 替换列表元素
alist[3:] = ['k', 'o', 'p', 'y']  # 从指定位置替换列表元素
alist[::2] = [0] * 5  # 隔一个修改一个
alist[::3] = ['a', 'b', 'c']
alist[:3] = []  # 删除前两个元素

print(alist)

4.获取列表长度

>>> list = [1,2,3,4,5]
>>> len(list)
5

5.列表操作

列表和字符串都属于有序序列,所以基本操作都相同

>>> [1,2,3] + [4,5,6]
[1, 2, 3, 4, 5, 6]

>>> list = [1,2,3]
#重复列表三次
>>> list * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

# 1是否在 list列表中
>>> 1 in list
True

# 1是否不在 list列表中
>>> 1 not in list 
False

# 删除
>>> del list[1]
>>> list
[1, 3]

6.常见列表操作函数

操作列表的函数

函数名描述示例结果
len(list)返回列表的长度len([1,2,3])3
max(list)返回列表元素中最大值max([1,2,3,4])4
min(list)返回列表元素中最小值min([1,2,3,4])1
list(tuple)将元组转换成listlist((1,2,3))[1,2,3]

列表包含方法

方法名描述示例结果
list.append(obj)在列表末尾添加新元素[1,2,3].append(4)[1,2,3,4]
list.count(obj)统计某个元素在列表中出现的次数[1,2,3,3,4,2,3,5].count(3)3
list.clear()清空列表[1,2,3,4].clear()[]
list.copy()浅拷贝一个列表list = [1,2,3].copy()[1,2,3]
list.extend(list)在列表末尾一次性追加另一个序列中的多个值[1,2,3].extend([4,5,6])[1,2,3,4,5,6]
list.index(obj)找出某个值第一个匹配项的索引位置[1,2,3,1,2].index(1)0
list.insert(ind,obj)将元素插入指定位置[1,2,3].insert(1,9)[1,9,2,3]
list.pop()移除列表中的一个元素(默认最后一个元素),并且返回该元素的值[1,2,3,4].pop()4
list.remove(obj)移除列表中某个值的第一个匹配项[1,2,3].remove(2)[1,3]
list.reverse反向列表中元素[1,2,3].reverse()[3,2,1]
list.sort()对原列表进行排序[2,3,6,4,7].sort()[2,3,4,6,7]

python3.7 入门教程

Python 准备工作(1) Python 基本数据类型 Number(2) Python 字符串 str(3) Python 列表List(4) Python 元组tuple(5) Python 集合set(6) Python 字典 dict(7) Python 变量(8) Python 运算符(9) Python 条件语句(10) Python 循环语句(11) Python 包 模块(12) Python 函数一(13) Python 函数二(14) Python 面向对象(15) Python 正则(16) Python json(17) Python 枚举(18) Python 闭包(19) Python 装饰器(20) Python 杂记(21) Python with(22)