Python序列(一) 列表与元组

来源:互联网 发布:手机淘宝店标怎么设置 编辑:程序博客网 时间:2024/06/05 00:37

序列:列表,字符串,元组,其中字符串和元组是不能改变的

序列的基本操作:
1.列表定义
2.index
3.分片
4.列表+,*
5.检测成员是否在序列中
6.字符串,元组序列化list
7.len(seq),max(seq),min(seq)
8.append(),sorted(),sort(),remove(),pop(),insert(),extend()
9.tuple()

序列操作#定义序列>>> a=["x1","x2"]>>> a['x1', 'x2']#使用序列中的元素>>> a[0]'x1'>>> a[-1]'x2'>>> a[-2]'x1'>>> b='hello'>>> b'hello'>>> b[0]'h'>>> b[-1]'o'#序列分片:访问序列的子序列>>> tag='123456'>>> tag'123456'>>> tag[1:3]'23'>>> tag[1:-1]'2345'>>> numbers=[1,2,3,4,5,6,7,8,9,10]>>> numbers[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>>> numbers[3:6][4, 5, 6]>>> numbers[0:1][1]#访问最后一个元素>> numbers[7:10] [8, 9, 10]>>> numbers[-3:-1][8, 9]>>> numbers[-3:][8, 9, 10]>>> numbers[-3:0][]>>> numbers[:][1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>>> numbers[:1][1]>>> numbers[1:10:3][2, 5, 8]>>> numbers[1:10:5][2, 7]>>> numbers[5:10:5][6]>>> numbers[10:5][]>>> numbers[10:5:-1][10, 9, 8, 7]#序列相加,必须为同等类型>>> numbers+[1,1,4][1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 1, 4]#检测成员是否在序列中>>> 1 in numbersTrue>>> 15 in numbersFalse#序列的最大值,最小值,长度>>> len(numbers)10>>> min(numbers)1>>> max(numbers)10>>> #修改字符串#序列化字符串>>> list("hello") //序列化字符串['h', 'e', 'l', 'l', 'o']>>> list("hello")[-1]='k'>>> i=list("hello")>>> i[-1]='k'>>> >>> i['h', 'e', 'l', 'l', 'k']>>> str(i)"['h', 'e', 'l', 'l', 'k']">>> i['h', 'e', 'l', 'l', 'k']>>> print(i)['h', 'e', 'l', 'l', 'k']>>> del(i[-1])>>> i['h', 'e', 'l', 'l']>>> i[2:]=list("ar")>>> i['h', 'e', 'a', 'r']>>> #列表方法>>> i.append("j")>>> i['h', 'e', 'a', 'r', 'j']>>> i.append("h")>>> i.count("h")2>>> b=[1,2,3,4]>>> i.extend(b)>>> i['h', 'e', 'a', 'r', 'j', 'h', 1, 2, 3, 4]>>> i.index("h")0>>> i.insert(4,"o")>>> i['h', 'e', 'a', 'r', 'o', 'j', 'h', 1, 2, 3, 4]>>> i.pop(4)'o'>>> i.remove("h")>>> i['e', 'a', 'r', 'j', 'h', 1, 2, 3, 4]>>> i.reverse()>>> i[4, 3, 2, 1, 'h', 'j', 'r', 'a', 'e']>>> a=i[:5]>>> a[4, 3, 2, 1, 'h']>>> a=i[:4]>>> a.sort()>>> a[1, 2, 3, 4]>>> a[1, 2]>>> a.reverse()>>> a[2, 1]>>> list(reversed(a))[1, 2]>>> b=list(reversed(a))>>> b[2, 1]>>> sorted(b)[1, 2]#元组>>> (1,2)(1, 2)>>> 11>>> 1,(1,)>>> 1,2,3(1, 2, 3)>>> ()()>>> tuple('abcd')('a', 'b', 'c', 'd')>>> tuple([2,3,4])(2, 3, 4)>>> a=(1,2,3,4)>>> a(1, 2, 3, 4)>>> a[1]2>>> i=a[:2]>>> i(1, 2)
0 0
原创粉丝点击