python入门到精通教程06-一文轻松搞懂python列表
列表定义
使用中括号[],里面的值可以为任意类型
list1 = ['hello',123,99.99,False]
列表特点
- 有序:下标索引
- 元素可修改
- 值可重复
列表值访问
- list[index]:索引从0开始,不能越界
- list[0]访问第一个值
列表新增
list.append(value):数组列表末尾新增
list.insert(index,value):在index位置插入value
列表修改
list[index]=value:列表索引index位置设置value
列表删除
list.pop():读取列表末尾的值并删除末尾的值
list.pop(index):读取列表索引index的值,并删除
list.remove(value):找到符合条件的第一个value删除
列表切片
列表运算
加法+,连接2个列表,合并成一个列表
list1 = ['hello']
list2 = ['world']
list3 = list1 + list2
print(list3) #输出:['hello','world']
乘法*,复制列表
list1= ['hello']
list2 = list1 *4 #将列表复制4次
print(list2) #输出:['hello','hello','hello','hello']
判断
value in list :判断value是否在列表list
value not in list:判断列表是否不存在列表list
列表常用方法
len(list):列表的长度
max(list):列表中元素最大值,必须是相同类型对比
min(list):列表中元素最小值,必须是相同类型对比
list(tuple):将元组转化为列表
列表常用其他方法
list.count(obj):统计某个元素的个数
list.extend(seq):在列表后面追加列表或其它序列
list.index(obj):查找元素索引值
list.reverse():反向列表中的元素
list2 = ['world','hello']
list3 = list2.reverse() #反向列表中的元素
print(list3) #输出:['hello','world']
list.sort(key=None,reverse=False):将列表排序,默认升序
list.clear():情况列表
list.copy():复制列表
嵌套列表
使用嵌套列表即在列表里创建其它列表
示例代码:
a = ['hello','world']
b = [123,456]
c= [a,b] #嵌套列表
print(c) #输出[['hello','world'],[123,456]]