python 列表 发表于 2019-10-22 | 更新于 2023-01-11 python列表练习123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122# python列表入门ls = [1, 2, 3, 4, 5, 6]# 获取对应下标print(ls[2])print(ls[-1])# 获取长度print(len(ls))# 切片: 包括起始位置,不包括结束位置,不影响原列表print(ls[1:2])print(ls[1:])# 复制列表print(ls[:])# 第三个参数表示间隔print(ls[1:5:2])# 列表累加a = [1, 2, 3, 4]b = [5, 6, 7, 8]print(a + b)# 列表复制print([1, 2, 3] * 3)# in 和 not inprint(1 in [1, 2, 3, 4])print(1 not in [1, 2, 3, 4])# min maxa = [1, 2, 3, 4, 5, 6, 2]print(min(a))print(max(a))# index: 出现的下标# count:出现的次数print(a.index(3))print(a.count(2))# 修改列表ls = ls2 = [1, 2, 3, 4]print(ls, ls2)ls[0] = 0print(ls, ls2)# del 删除元素ls = [1, 2, 3, 4]del ls[2]# del ls{::2}# del ls[1:]print(ls)# 切片赋值,必须传入序列,不可以是数字ls = [1, 2, 3, 4]ls[0:2] = 'ab'print(ls)ls = [1, 2, 3, 4]# ls[0:2] = ['a', 'b', 'c', 'd'] # ['a', 'b', 3, 4]ls[0:2] = 'a' # ['a', 3, 4]print(ls)# 插入ls = [1, 2, 3, 4]ls[1:1] = '插入'print(ls)# 类型转换a = '1234'print(list(a))# 最后拆入ls = [0, 1, 2]ls.append('a')print(ls)# axtend 相当于 +=# 插入(下标,元素)ls = [0, 1, 2]ls.insert(1, 'aa')print(ls)# 清空ls.clear()print('清空', ls)# pop 删除返回删除元素ls = [0, 1, 2]ls.pop(1)print(ls)# 删除,只删除第一个ls = [1, 2, 2, 3, 4]ls.remove(2)print('remove: ', ls)# 反序ls = [1, 2, 3, 4]ls.reverse()print('反序:', ls)# 排序 sortls = [1, 0, 2, 4]# ls.sort() # 正序ls.sort(reverse=True) # 倒序print('sort', ls)# while遍历列表# ls = [0, 1, 2, 3]# i = 0# while i < len(ls):# print(ls[i])# i += 1# for 循环ls = ['a', 'b', 'c']for i in ls: print(i)