日期:
来源:雷子说测试开发收集编辑:雷子V
上一篇
本次分享列表
正文
序列是 Python 中最基本的数据结构。如何定义呢
>>> listone=[1,2,3]>>> listone[1, 2, 3]>>> listtwo=['name']>>> listtwo['name']>>> listtree=['name',1]>>> listtree['name', 1]
序列中的每个值都有对应的位置值,称之为索引,第一个索引是 0,第二个索引是 1,依此类推。那么我们去获取下list的第一个
>>> listone=[1,2,3]>>> listone[0]1
这样,我们从列表中去获取对应的数据。那么这个是从左到右的,如果想取右边的第一个如何获取呢?
>>> listone=[1,2,3]>>> listone[-1]3
这样获取第一个是-1 获取第二个就是-2,然后依次类推。
如果我们想要截取一部分呢,这个是字符串的一样,也是前包括后不包括
>>> listone=[1,2,3]>>> listone[1:-1][2]>>> listone=[1,2,3,4,5,6,7]>>> listone[2:][3, 4, 5, 6, 7]
Python 有 6 个序列的内置类型,但最常见的是列表和元组。
更新列表的内容,比如第1个更改
>>> listone=[1,2,3,4,5,6,7]>>> listone[0]='A'>>> listone['A', 2, 3, 4, 5, 6, 7]
那么想要添加怎么办呢
>>> listone['A', 2, 3, 4, 5, 6, 7]>>> listone.append('A')>>> listone['A', 2, 3, 4, 5, 6, 7, 'A']#指定位置增加>>> listone[1, 2, 3, 4, 5, 11]>>> listone.insert(1,'1')>>> listone[1, '1', 2, 3, 4, 5, 11]
删除元素
>>> listone['A', 2, 3, 4, 5, 6, 7, 'A']>>> del listone[0]>>> listone[2, 3, 4, 5, 6, 7, 'A']#删除指定的元素>>> listone.remove(2)>>> listone[3, 4, 5, 6, 7, 'A']#如果相同的元素的删除,会删除左边的第一个>>> listone[3, 4, 5, 6, 7, 'A', 'A', 'B', 'A']>>> listone.remove('A')>>> listone[3, 4, 5, 6, 7, 'A', 'B', 'A']#删除指定位置>>> listone=[3, 4, 5, 6, 7, 'A', 'B', 'A']>>> listone.pop(3)6>>> listone[3, 4, 5, 7, 'A', 'B', 'A']
获取list的长度
>>> listone[3, 4, 5, 6, 7, 'A', 'B', 'A']>>> len(listone)8>>> listone.__len__()8
list拼接
>>> [1,2,3]+[4,5][1, 2, 3, 4, 5]#extend也可以实现list拼接,但是在后面去追加的>>> two=['A']>>> listone[3, 4, 5, 6, 7, 'A', 'B', 'A']>>> two=['A']>>> listone.extend(two)>>> listone[3, 4, 5, 6, 7, 'A', 'B', 'A', 'A']
判断是否在
>>> listone[3, 4, 5, 6, 7, 'A', 'B', 'A', 'A']>>> 3 in listoneTrue
for循环
>>> for item in listone:... print(item)...34567ABAA
返回最大值
>>> listone[1, 2, 3, 4, 5]>>> max(listone)5
返回最小值
>>> min(listone)1
查找元素出现的个数
>>> listone[1, 2, 3, 4, 5]>>> listone.count(1)1
查询元素的索引
>>> listone.index(5)4
列表的反转
>>> listone[3, 4, 5, 7, 'A', 'B', 'A']>>> listone.reverse()>>> listone['A', 'B', 'A', 7, 5, 4, 3]
排序(int类型)
>>> listone=[1, 2, 4, 5, 11]>>> listone.sort()>>> listone[1, 2, 4, 5, 11]#降序>>> listone.sort(reverse=True)>>> listone[11, 5, 4, 2, 1]>>> listone.sort(reverse=True)>>> listone[11, 5, 4, 2, 1]
列表清空
>>> listone[11, 5, 4, 2, 1]>>> listone.clear()>>> listone[]
列表复制
>>> listone=[1, 2, 4, 5, 11]>>> name=listone.copy()>>> name[1, 2, 4, 5, 11]
复制后,如果修改列表的元素,不会修改复制后的元素。
>>> listone=[1, 2, 4, 5, 11]>>> name=listone.copy()>>> name[1, 2, 4, 5, 11]>>> listone[1]=22>>> name[1, 2, 4, 5, 11]
列表推导式
如何实现列表推导式,格式如下
[表达式 for 变量 in 列表]或者[表达式 for 变量 in 列表 if 条件]
演示
>>> listone=[1, 2, 4, 5, 11]>>> print([x*2 for x in listone])[2, 4, 8, 10, 22]>>> print([x for x in range(10)])[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]#复杂的>>> ([x*y for x in [1,2] for y in [2,3]] )[2, 3, 4, 6]>>> ([x*y for x in [1,2] for y in [2,3,4]] )[2, 3, 4, 4, 6, 8]#还可以增加if条件,直接演示>>> ([x*y for x in [1,2] for y in [2,3,4] if x !=1] )[4, 6, 8]