python 列表方法

来源:互联网 发布:淘客发单软件 编辑:程序博客网 时间:2024/06/06 01:42
#coding=utf-8#列表方法(append,count,extend,index,insert,pop,remove,reverse,sort)'''调用格式:对象.方法(参数)'''#appendlst=['a','b','c']lst.append('d')lst.append(9)print lst               #发现lst在末尾添加一个成员print type(lst)         #lst类型为listprint type(lst[3])      #添加的9转为str类型'''['a', 'b', 'c', 'd', 9]<type 'list'><type 'str'>'''#countlst.append('a')         #添加aprint lst.count('a')    #计数a个数,2#extend--在列表末尾一次性追加另一个序列的多个值a=[1,2,3]b=[4,5,6]a.extend(b)             #将b列表添加到a列表,a列表被改变print a'''[1, 2, 3, 4, 5, 6]'''#index从列表中找出某个值第一个匹配的索引位置linux=['link','addr','bcast','mask','scope','addr']print linux.index('addr')       #返回第一次索引到的位置print linux.index('mask')       #索引是从0开始,对应索引3# print linux.index('home')       #可以判断在列表中是否存在某个值'''ValueError: 'home' is not in list[1, 2, 3, 4, 5, 6]13'''#insert将对象到列表中numbers=[1,3,4,5,7]numbers.insert(1,2)numbers.insert(5,'6')print numbers'''[1, 2, 3, 4, 5, '6', 7]'''#pop移除列表中的一个元素x=[1,2,3,4,5]x.pop()                     #类似栈,取出最顶端的print xx.pop(0)                    #取出0下标对应的索引值print x'''[1, 2, 3, 4][2, 3, 4]'''#remove移除列表中某个值的第一个匹配项y=['hello','boy','hello','girl']y.remove('hello')           #此处移除第一个匹配的'hello'print y'''['boy', 'hello', 'girl']'''#reverse将列表的元素取反存放z=[1,2,3,4,5]z.reverse()print z'''[5, 4, 3, 2, 1]'''#sort对列表进行排序w=[1,4,6,8,2,5,9]w.sort()                    #默认为升序print w'''[1, 2, 4, 5, 6, 8, 9]'''
0 0
原创粉丝点击