list python数据类型-列表

Python中列表是最常用的数据类型之一 , 由多个元素组成的集合 , 每个元素都有一个位置或者叫索引 , 索引的值从0开始 , 往后顺序递推 , 最大值为列表长度-1
例如
aa = [1, 2, 3, 4, 5]print(aa[0])# 1print(aa[1])# 2print(aa[2])# 3常用方法索引、切片#索引 切片l = ['a', 'b', 'c', 'd', 'e', 'f']# 优先掌握部分print(l[1:5])print(l[1:5:2])print(l[2:5])print(l[-1])"""['b', 'c', 'd', 'e']['b', 'd']['c', 'd', 'e']f"""# 了解print(l[-1:-4])print(l[-4:-1])print(l[-4:])l = ['a', 'b', 'c', 'd', 'e', 'f']print(l[-2:])"""[]['c', 'd', 'e']['c', 'd', 'e', 'f']['e', 'f']"""追加元素Append()hobbies = ['play', 'eat', 'sleep', 'study']hobbies.append('girls')print(hobbies) # ['play', 'eat', 'sleep', 'study', 'girls']删除元素pop()如果pop()里面没加参数 则默认删除最后一个元素
hobbies = ['play', 'eat', 'sleep', 'study', 'run', "girl"]x = hobbies.pop(1)# 不是单纯的删除 , 是删除并且把删除的元素返回 , 我们可以用一个变量名去接收该返回值print(x)print(hobbies)x = hobbies.pop(0)print(x)x = hobbies.pop(0)print(x)x = hobbies.pop()print(x)"""eat['play', 'sleep', 'study', 'run', 'girl']playsleepgirl"""deldel和pop() 不一样 ,  他没有返回值 , 只是单纯的将参数里面索引对应的元素从列表里面删除
这种删除方式不光在列表中有用 , 在后面的元组和字典里也是有用的
hobbies = ['play', 'eat', 'sleep', 'study']del hobbies[1]# 单纯的删除print(hobbies)# ['play', 'sleep', 'study']remove()remove()参数是具体的元素值,不是索引 , 也没有返回值
hobbies = ['play', 'eat', 'sleep', 'study']hobbies.remove('eat')# 单纯的删除 , 并且是指定元素去删除print(hobbies)# ['play', 'sleep', 'study']用append()和pop()队列和堆栈队列:是一种数据结构 , 其特点是先进先出 , 就和排队一样 , 排在最前面的人优先买到东西
堆栈: 是一种数据结构 , 其特点是后进先出 , 就和往桶里面放东西一样 , 最后放进去的,往往是最先拿出来
# 队列:先进先出queue_l = []# 入队queue_l.append('first')queue_l.append('second')queue_l.append('third')print(queue_l)# ['first', 'second', 'third']# 出队print(queue_l.pop(0))# firstprint(queue_l.pop(0))# secondprint(queue_l.pop(0))# third# 堆栈:先进后出 , 后进先出l = []# #入栈l.append('first')l.append('second')l.append('third')# #出栈print(l)# ['first', 'second', 'third']print(l.pop())# thirdprint(l.pop())# secondprint(l.pop())# first计算列表的长度hobbies=['play','eat','sleep','study']print(len(hobbies))# 4列表是否包含某个元素对于字符串来说也是可以的
#包含inhobbies = ['play', 'eat', 'sleep', 'study']print('sleep' in hobbies)# Truemsg = 'hello world sz'print('sz' in msg)# True插入元素insert()hobbies = ['play', 'eat', 'sleep', 'study', 'eat', 'eat']hobbies.insert(1, 'walk')print(hobbies)hobbies.insert(1, ['walk1', 'walk2', 'walk3'])print(hobbies)"""['play', 'walk', 'eat', 'sleep', 'study', 'eat', 'eat']['play', ['walk1', 'walk2', 'walk3'], 'walk', 'eat', 'sleep', 'study', 'eat', 'eat']"""统计个数count()hobbies = ['play', 'eat', 'sleep', 'study', 'eat', 'eat']print(hobbies.count('eat'))# 3列表合并extend()list1.extend(list2) 将list2中的元素从list1的末尾添加上list1中
hobbies = ['play', 'eat', 'sleep', 'study', 'eat', 'eat']hobbies.extend(['walk1', 'walk2', 'walk3'])print(hobbies)# ['play', 'eat', 'sleep', 'study', 'eat', 'eat', 'walk1', 'walk2', 'walk3']


推荐阅读