python列表命令
创建普通列表:member;; 创建混合列表:mix; 创建空列表:empty
>>> member = ['lala','oo'] >>> member ['lala', 'oo'] >>> member.append('jjj') >>> member ['lala', 'oo', 'jjj'] >>> len(member) 3 >>> member.extend(['xx','pp']) >>> member ['lala', 'oo', 'jjj', 'xx', 'pp'] >>> len (member ) 5 >>> member .insert(0,'ll') >>> member ['ll', 'lala', 'oo', 'jjj', 'xx', 'pp'] >>>
append()只能添加一个
extend() 扩展一个列表
insert()排列或插入,排序要从0开始
从列表中获取元素
通过元素的索引值(index)从列表中获取单个元素,从0开始
用temp可以改变位置
>>> member ['ll', 'lala', 'oo', 'jjj', 'xx', 'pp'] >>> member [0] 'll' >>> temp = member [0]>>> member [0] = member [1] >>> member ['lala', 'lala', 'oo', 'jjj', 'xx', 'pp'] >>> member [1] = temp >>> member ['lala', 'll', 'oo', 'jjj', 'xx', 'pp'] >>>
从列表删除元素
1:remove()
2:del
3:pop() 从列表中取出一个元素
>>> member ['lala', 'll', 'oo', 'jjj', 'xx', 'pp'] >>> member.remove ('ll') >>> member ['lala', 'oo', 'jjj', 'xx', 'pp']>>> del member [1] >>> member ['lala', 'jjj', 'xx', 'pp'] >>> member .pop() 'pp' >>> member ['lala', 'jjj', 'xx'] >>> name = member .pop() >>> name 'xx' >>> member ['lala', 'jjj'] >>> member .pop(1) 'jjj' >>> member ['lala']
利用列表分片:slice
>>> member [1:3]
1代表开始,3代表结束 0:可以不用写 最后也可以不用写, 都不写可以拷贝文件
>>> member ['小耿哥', '耿哥 ', 'lala', 'haha'] >>> member [1:3] ['耿哥 ', 'lala'] >>> member ['小耿哥', '耿哥 ', 'lala', 'haha'] >>> member [:3] ['小耿哥', '耿哥 ', 'lala'] >>> member [:] ['小耿哥', '耿哥 ', 'lala', 'haha'] >>> member2 = member [:] >>> member2 ['小耿哥', '耿哥 ', 'lala', 'haha']
列表常用操作符
1:比较操作符
2:逻辑操作符
3:连接操作符
4:重复操作符
5:成员关系操作符
>>> list1 = [123,234] >>> list2 = [345,456] >>> list1 > list2 False >>> list3 = [123,234] >>> (list1 < list2) and (list1 == list3) True >>> list4 = list1 + list3 >>> list4 [123, 234, 123, 234] >>> 不能添加新元素 >>> list3 * 3 [123, 234, 123, 234, 123, 234] >>> list3 *= 3 >>> list3 [123, 234, 123, 234, 123, 234] >>> 123 in list3 True >>> list5 = [123,['小耿哥'],456] >>> '小耿哥' in list5[1] True >>> '用索引号去访问列表的值' '用索引号去访问列表的值' >>> list5[1][0] '小耿哥'
列表的小伙伴
count:计算参数在列表的次数
index:索引
reverse:逆行
sort:指定方式排序
>>> list3.count(123) 3 >>> list3.index(123) 0 >>> list3.index(123,3,7) 4 >>> list3.reverse() >>> list3 [234, 123, 234, 123, 234, 123] >>> list6 = [4,3,6,4,98,54,54,41] >>> list6.sort() >>> list6.sort() >>> list6] SyntaxError: invalid syntax >>> list6 [3, 4, 4, 6, 41, 54, 54, 98] >>> list6.sort(reverse=True) >>> list6 [98, 54, 54, 41, 6, 4, 4, 3]
元组:不可以被修改
元组跟列表很相似
>>> tuple1 = (1,2,3,4,5,6,7,8) >>> tuple1 (1, 2, 3, 4, 5, 6, 7, 8) >>> tuple1[1] 2 >>> tuple1[5:] (6, 7, 8) >>> tuple2 = tuple1[:] >>> tuple2 (1, 2, 3, 4, 5, 6, 7, 8) >>> temp = (1) >>> temp 1 >>> temp2 = 2,3,4 >>> type(temp2) <class 'tuple'> >>> type(temp) <class 'int'> >>> 8 * (8) 64 >>> 8 * (8,) (8, 8, 8, 8, 8, 8, 8, 8) >>> '跟逗号有关' '跟逗号有关' >>> temp = ('小耿哥','古风歌','耿哥','哈哈啊') >>> temp ('小耿哥', '古风歌', '耿哥', '哈哈啊') >>> temp = temp[:2] + ('啦啦',) + temp[2:] >>> temp ('小耿哥', '古风歌', '啦啦', '耿哥', '哈哈啊')
小胖专属学习分享