列表数据类型的内置方法
1.作用
列表的作用就是可以描述多个值,就比如一个人可以有很多的爱好
2.定义方式
hobby_list = ['play', 'swimming', 'dancing']
print(hobby_list)
lt = list('randysun')
print(lt)
3.内置方法
优先掌握
-
索引取值
hobby_list = ['play', 'swimming', 'dancing'] print(hobby_list[-1]) hobby_list[0] = '2233' print(hobby_list) print(hobby_list[::-1])
-
切片
hobby_list = ['play', 'swimming', 'dancing'] print(hobby_list[:]) #输出:['play', 'swimming', 'dancing'] print(hobby_list[::-1]) #输出:['dancing', 'swimming', 'play']
-
长度
hobby_list = ['play', 'swimming', 'dancing'] print(len(hobby_list)) 获取hobby——list的长度 #输出:3
-
in/not in
hobby_list = ['play', 'swimming', 'dancing'] print('swimming' in hobby_list) #输出 True
-
for循环
hobby_list = ['play', 'swimming', 'dancing'] for hooby in hobby_list: print(hooby) #依次输出hobby_list
-
删除del
hobby_list = ['play', 'swimming', 'dancing'] del hobby_list #删除全部 del hobby_list[-1] #删除从右往左第一个
-
追加
hobby_list = ['play', 'swimming', 'dancing'] hobby_list.append('123') #在最后米娜追加 print(hobby_list)
需要掌握
hobby_list = ['play', 'swimming', 'dancing', '1', '1']
-
统计列表内某一个元素出现的次数
print(hobby_list.count('')) #输出 0 print(hobby_list.count('1')) #输出 2
-
扩展列表
hobby_list.extend([1,2,3,4]) print(hobby_list) #输出:['play', 'swimming', 'dancing', '1', '1', 1, 2, 3, 4]
-
清除
print(hobby_list.clear()) #输出 []
-
复制列表
hobby_list2 = hobby_list.copy() print(hobby_list2)
-
删除(默认删除最后一个)
hobby_list.pop() print(hobby_list)
-
索引
print(hobby_list.index('play')) print(hobby_list.index('play',2,4)) #索引2-4 内有没有该值
-
插入
hobby_list.insert(0, "1") #索引0的位置插入字符1 print(hobby_list)
-
移除(只会删除一个)
-
移除,只会删除一个
hobby_list = ['play', 'swimming', 'dancing', '1', '1'] print(hobby_list) hobby_list.remove('1') print(hobby_list)
-
反转
hobby_list.reverse() print(hobby_list)
-
排序
hobb_list = [1,0,45,120,77,3] hobby_list.sort() print(hobby_list00000000000000000000000.242.0000000000)
4.存一个值还是多个值
存在多个值
5.有序or无序
有序(可索引)
6.可变or不可变(重点)
可变
可变:值变id不变
不可变:值变id也变
lis = [1, 1, 2, 3, 4, 5]
print(lis)
print(id(lis))
lis.append(100)
print(lis)
print(id(lis))
标签:play,内置,dancing,数据类型,list,列表,print,hobby,swimming
From: https://www.cnblogs.com/JunLeewarehouse/p/17688902.html