列表相关操作
一、列表的创建
1、列表需要使用中括号 [] 和 , 元素之间使用英文的逗号进行分隔
2、列表的创建方式有两种
- 使用中括号
- 调用内置函数list()
#列表的创建 #第一种方法:使用中括号 mylist=['hello','world',98] print(id(mylist)) print(type(mylist)) print(mylist) #第二种方法:调用内置函数list() mylist2=list(['hello','world',98]) print(id(mylist2)) print(type(mylist2)) print(mylist2) 运算结果: 2610096938048 <class 'list'> ['hello', 'world', 98] 2610096986688 <class 'list'> ['hello', 'world', 98]
二、列表的特点
1、列表的元素按顺序有排序
2、索引映射唯一数据
- 顺序从0开始
- 逆序从-1开始
3、列表可以存储重复数据
4、任意数据类型混存
5、根据需要动态分配和回收内存
三、列表的查询操作
1、获取列表中的指定元素的索引
- 如果列表中存在N个相同元素,只返回相同元素中的第一个元素的索引
- 如果查询的元素在列表中不存在,则会抛出ValueError
- 还可以在指定的start和stop之间进行查找
#列表的查找
mylist3=['hello','world',98,'hello']
print(mylist3)
print(mylist3.index('hello'))
#rint(mylist3.index('sha')) 报错:ValueError: 'sha' is not in list
#可以在index中指定查找范围 【a,b)
#print(mylist3.index('hello',1,3)) 报错:NameError: name 'hello' is not defined(因为在该范围内没有找到)
print(mylist3.index('hello',1,4))
运行结果:
['hello', 'world', 98, 'hello']
0
3
2、获取列表中的单个元素
正向索引从0到N-1 举例:lst[0]
逆向索引从-N到-1 举例:lst[-N]
指定索引不存在 抛出异常indexError
3、获取列表中的多个元素——切片
- 语法格式:【start : stop : step】
- 切片操作:
- 切片结果:原列表片段的拷贝——生成新的列表
- 切片的范围:【start , stop)
- step默认为1:简写为[start:stop]
- step为正数:从start开始向后计算切片
- step为负数:从start开始向前计算切片
lst=[10,20,30,40,50,60,70,80]
#start=1,stop=6,step=1
print(lst[1:6:1]) #lst的标号从0开始,sto=6其实是第七个元素,但是不包含该数据
#切片是产生了一个新的列表,可以发现两者id值不一样,说明产生了一个新的列表
print('原列表',id(lst))
lst2=lst[1:6:1]
print('现列表',id(lst2))
#查看默认步长
print(lst[0:6:]) #[10, 20, 30, 40, 50, 60]可以发现默认步长为1
#设置步长
print(lst[1:6:2]) #[20, 40, 60]
#查看默认开始位置
print(lst[:6:]) #[10, 20, 30, 40, 50, 60]可以发现默认开始位置为0
#设置开始位置
print(lst[2:6:1]) #[30, 40, 50, 60]
#查看默认结束位置
print(lst[1::1]) #[20, 30, 40, 50, 60, 70, 80]可以发现默认结束位置是整个列表
#全部设置默认
print(lst[::]) #[10, 20, 30, 40, 50, 60, 70, 80]相当于对列表的一次复制
#如果步长为负数-从后向前
print(lst[::-1]) #[80, 70, 60, 50, 40, 30, 20, 10]
print(lst[7:0:-1])#[80, 70, 60, 50, 40, 30, 20] 结尾到0但不包括0
4、判断指定元素在列表中是否存在
元素 in 列表名
元素 in 列表名
print('k' in 'kotlin')#True
print('k' in 'python')#False
lst=[10,20,'hello','python']
print(10 in lst) #True
print(100 in lst) #False
print(10 not in lst) #False
print(100 not in lst)#True
5、列表元素的遍历
#列表的遍历,用for循环
for i in lst:
print(i)
运算结果:
10
20
hello
python
浙公网安备 33010602011771号