Python基础教程笔记——列表和元组
#检查值是否在序列中>>> mystr="this is a string">>> 'this' in mystrTrue2.6 长度,最大值,最小值
#min,max和len的用法>>> data = [12,31,2,1,3,12,3,13,131234,12]>>> min(data)1>>> max(data)131234>>> len(data)103 列表:Python的“苦力”
?
3.1 list>>> list("This is a test string")['T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', ' ', 's', 't', 'r', 'i', 'n', 'g']3.2 基本列表操作
>>> mylist = [1,2,3,4,5]#列表元素赋值#索引必须在列表范围内>>> mylist[10] = 10Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> mylist[10] = 10IndexError: list assignment index out of range>>> mylist[0] = 100>>> mylist[100, 2, 3, 4, 5]#删除元素>>> del(mylist[0])>>> mylist[2, 3, 4, 5]>>>#分片赋值>>> mystr = list("Nale Gunn")>>> mystr[0:4] = list("Bill")>>> mystr['B', 'i', 'l', 'l', ' ', 'G', 'u', 'n', 'n']#分片赋值时,原片与新片长度不同>>> mystr=list("Bill Gunn")>>> mystr[-5:] = list("gunn@gmail.com")>>> mystr['B', 'i', 'l', 'l', 'g', 'u', 'n', 'n', '@', 'g', 'm', 'a', 'i', 'l', '.', 'c', 'o', 'm']>>>#分片赋值可以在指定位置插入新的元素>>> mystr=list("Bill Gunn")>>> mystr[0:0] = list("My name is ")>>> mystr['M', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' ', 'B', 'i', 'l', 'l', ' ', 'G', 'u', 'n', 'n']>>>3.3 列表方法
#append>>> lst = list("Test")>>> lst.append(list("String"))>>> lst['T', 'e', 's', 't', ['S', 't', 'r', 'i', 'n', 'g']]>>> lst.append("String")>>> lst['T', 'e', 's', 't', ['S', 't', 'r', 'i', 'n', 'g'], 'String']>>> lst=list("Test")>>> lst.append("!")>>> lst['T', 'e', 's', 't', '!']#count>>> lst.count('T')1>>> lst.count('t')1#extend>>> lst.extend(list("HaHa"))>>> lst['T', 'e', 's', 't', '!', 'H', 'a', 'H', 'a']>>> lst.index('t')3>>> #pop>>> lst = [1,2,3]>>> lst.pop()3>>> lst[1, 2]>>> lst.pop(0)1>>> lst[2]>>> #pop>>> lst = [1,2,3]>>> lst.pop()3>>> lst[1, 2]>>> lst.pop(0)1>>> lst[2]#remove>>> lst=list("12345678")>>> lst['1', '2', '3', '4', '5', '6', '7', '8']#删除不存在的对象会报错>>> lst.remove(2)Traceback (most recent call last): File "<pyshell#42>", line 1, in <module> lst.remove(2)ValueError: list.remove(x): x not in list>>> lst.remove('2')>>> lst['1', '3', '4', '5', '6', '7', '8']#reverse>>> lst.reverse()>>> lst['8', '7', '6', '5', '4', '3', '1']#sort>>> lst.sort()>>> lst['1', '3', '4', '5', '6', '7', '8']>>> lst.sort(key=len)>>> lst['1', '3', '4', '5', '6', '7', '8']>>> lst = ['asdf','qwersf','aaf','s','afasfd','qre']>>> lst.sort(key=len)>>> lst['s', 'aaf', 'qre', 'asdf', 'qwersf', 'afasfd']>>> lst.sort(key=len,reverse=True)>>> lst['qwersf', 'afasfd', 'asdf', 'aaf', 'qre', 's']>>> #列表复制>>> x = list('123456')#下面的复制,只是让y也指向x指向的对象,所以修改x,也会影响y的值>>> y = x>>> x.reverse()>>> y['6', '5', '4', '3', '2', '1']#用分片的方法复制,x与y相互独立,修改x,不会影响y>>> y=x[:]>>> y.sort()>>> x['6', '5', '4', '3', '2', '1']>>> y['1', '2', '3', '4', '5', '6']>>>4 元组
?
4.1 元组定义:#一般元组>>> 1,2,3(1, 2, 3)>>> (1,2,3)(1, 2, 3)#一个元素的元组>>> (1,)(1,)>>> 2,(2,)#空元组>>> ()()>>> #元组的乘法>>> 4* (2,)(2, 2, 2, 2)>>>4.2 tuple函数
>>> tuple("CONSTANT")('C', 'O', 'N', 'S', 'T', 'A', 'N', 'T')>>> tuple(list("CONST"))('C', 'O', 'N', 'S', 'T')>>>4.3 元组的意义: