列表数据类型内置方法
1.作用
描诉多个值,比如爱好
2.定义方式
hobby_list = ['play', 'swim', 'dancing', '666']
print(hobby_list)
3.内置方法
优先掌握
1.索引取值
hobby_lsit=['play','dance','jump','666']
print(hobby_lsit[-1])
hobby_lsit[-1]='233'
print(hobby_lsit[-1])
666,233
2.切片
hobby_lsit=['play','dance','jump','666']
print(hobby_lsit[:])
print(hobby_lsit[::-1])
['play', 'dance', 'jump', '666']
['666', 'jump', 'dance', 'play']
3.长度
hobby_lsit=['play','dance','jump','666']
print(len(hobby_lsit))
4
4.in/not in
hobby_list = ['play', 'swim', 'dancing', '666']
print('play' in hobby_list)
True
5.for循环
hobby_list=['play','dance','jump','666']
for hobby in hobby_list:
print(hobby)
play
dance
jump
666
6.del删除
hobby_list=['play','dance','jump','666']
del hobby_list[-1]
print(hobby_list)
['play', 'dance', 'jump']
7.append() 追加
hobby_lsit=['play','dance','jump','666']
hobby_lsit.append('dapao-->sword')
print(hobby_lsit)
['play', 'dance', 'jump', '666', 'dapao-->sword']
需要掌握
1.count 对列表内某一个元素计数
hobby_lsit=['play','dance','jump','666',666,666]
print(hobby_lsit.count(666))
2
2.extend 扩展列表
hobby_lsit=['play','dance','jump','666',666,666]
hobby_lsit.extend([1,2,3,4])
print(hobby_lsit)
['play', 'dance', 'jump', '666', 666, 666, 1, 2, 3, 4]
3.clear 清除
hobby_lsit=['play','dance','jump','666',666,666]
hobby_lsit.clear()
print(hobby_lsit)
[]
4.copy 复制列表
hobby_list=['play','dance','jump','666',666,666]
hobby_list_2=hobby_list.copy()
hobby_list[-1]='233'
print(hobby_list)
print(hobby_list_2)
['play', 'dance', 'jump', '666', 666, '233']
['play', 'dance', 'jump', '666', 666, 666]
5.pop 删除,默认删除最后一个
hobby_list=['play','dance','jump','666',666,666]
hobby_list.pop()
print(hobby_list)
['play', 'dance', 'jump', '666', 666]
6.index 索引
hobby_list=['play','dance','jump','666',666,666]
print(hobby_list.index('play'))
print(hobby_list.index('jump',1,3)) #索引1-3内有没有该值
0
2
7.insert 插入
hobby_list=['play','dance','jump','666',666,666]
hobby_list.insert(0,'1')
print(hobby_list)
'1', 'play', 'dance', 'jump', '666', 666, 666]
8.移除 remove
hobby_list=['play','dance','jump','666',666,666]
hobby_list.insert(0,'1')
print(hobby_list)
hobby_list.remove('1')
print(hobby_list)
['1', 'play', 'dance', 'jump', '666', 666, 666]
['play', 'dance', 'jump', '666', 666, 666]
9.反转 reverse
hobby_list=['play','dance','jump','666',666,666]
hobby_list.insert(0,'1')
print(hobby_list)
hobby_list.reverse()
print(hobby_list)
['1', 'play', 'dance', 'jump', '666', 666, 666]
[666, 666, '666', 'jump', 'dance', 'play', '1']
10.sort 排序 使用sort列表的元素必须是同类型的
name_list = ['aden','nick', 'jason', 'tank', 'sean']
name_list.sort()
print(name_list)
['aden', 'jason', 'nick', 'sean', 'tank']
4.存一个值还是多个值
多个值
5.有序or无序
有序
6.可变or不可变
可变
lis = [12, 14]
print(id(lis))
lis.append('l1')
print(id(lis))
2379100691848
2379100691848