python 序列
序列数据结构:list,tuple,str
其他数据结构:set,dict
列表
1、增删改查
注意:1、列表是可变序列,所有的操作都是改变本身,也就是说ID不会改变的,只改变了存储的内容。
2、列表是以类的形式实现的,“创建”列表实际上是将一个类实例化。
3、列表的方法大多数都是针对一维的列表有效,对多维列表是无效的。
4、有返回值的方法如下所示:
返回值 | |
---|---|
list2.copy() | 返回被复制的新列表,且id不一样 |
copy.deepcopy(a) | 返回被复制的新列表,且id不一样 |
list6.pop() | 返回被删除的元素值 |
list8.index('a') | 返回匹配到的第一个索引 |
list2[1] | 有返回值,返回索引对应的值 |
list10.count('34') |
增--------------------------------------------------------------------------------------------------- # append()末尾追加元素,这个元素类型没有限制,和下边extend()做对比 >>> list3 = ['111','hello', 3333] >>> list3.append('2222') # 无返回值,但改变了列表本身 >>> list3 ['111', 'hello', 3333, '2222'] >>> list3.append((555,['a','b'])) # append只接受一个参数 >>> list3 ['111', 'hello', 3333, '2222', (555, ['a', 'b'])] # extend()该方法只能追加可迭代对象(序列),不能是数值类型的元素 >>> list4 = ["9", 9] >>> list4.extend([1,2]) # 无返回值,但改变了列表本身 >>> list4 ['9', 9, 1, 2] >>> list4.extend(((1,2),[3,4],{'a':1,'b':2})) # extend()只能接收一个参数 ['9', 9, 1, 2, (1, 2), [3, 4], {'a': 1, 'b': 2}] >>> list4.extend("python") # 这里要注意:他只把字符串当作是序列来处理,而不是数值,效果看打印 >>> list4 ['9', 9, 1, 2, (1, 2), [3, 4], {'a': 1, 'b': 2}, 'p', 'y', 't', 'h', 'o', 'n'] >>> list4.extend(1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not iterable # 提示object不是可迭代对象 # insert()指定对象插入列表的指定位置,注意insert是插在前面,list5.insert(-1,'a') >>> list5 = ['aaa', 'bbb', 'ccc'] >>> list5.insert(0,1) # 无返回值,但改变了列表本身 >>> list5 [1, 'aaa', 'bbb', 'ccc'] >>> list6 = [] >>> list6.insert(0, 1) >>> list6 [1] >>> list5 = [] >>> list5.insert(-1, 'a') >>> list5.insert(-1, 'b') >>> list5 ['b', 'a'] # 注意这里为什么b会在a的前面,就是因为insert是占的a的位置,把a挤到后面去了 >>> 删--------------------------------------------------------------------------------------------------- # remove()移除列表中某个值的第一个匹配项。注意和pop对比 >>> list7 = ['hello', 'world', 'hello', 'python'] >>> list7.remove("hello") # 他移除了靠前的"hello",无返回值,但改变了列表本身 >>> list7 ['world', 'hello', 'python'] >>> list7.remove("xxxx") # 要移除的值必须在列表中,否则报错 Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: list.remove(x): x not in list # pop()根据索引移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。 >>> list6 = ['a', 'b', 'c', 'd'] >>> list6.pop() # 有返回值,返回被删除的元素值 'd' >>> list6.pop(0) 'a' >>> list6.pop(5) # 注意索引必须在列表中存在 Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: pop index out of range # 索引不在列表之内 >>> list6.pop((0,2)) # 注意他只接收一位整数 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object cannot be interpreted as an integer # object不能解释为整数 # del 可以删除元素,也可以删除整个列表 >>> list1 [9, 1, 2, 'a', 3] >>> del list1[1] >>> list1 [9, 2, 'a', 3] >>> del list1
>>> list1 # 注意del删除整个列表是包括定义也一起删除了,而clear只是清空了容器 Traceback (most recent call last): #里面的内容,定义没删除 File "<stdin>", line 1, in <module> NameError: name 'list1' is not defined # clear()清空列表 >>>list1 = [1, 2, 'a'] >>>list1.clear() >>>list1 [] 改--------------------------------------------------------------------------------------------------- # [] 通过索引来改值 >>> a = [1,2,3] >>> a[0]='a' >>> a ['a', 2, 3] # [1:4:2] 根据切片来改 >>> a = [1,2,3] >>> a[1:3] = [66,99,77] [1, 66, 99, 77] # 注意当位数大于切片的长度时,多余的元素也会插入到列表中 >>> list1 [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> list1[slice(1,6,2)] = ['a', 'b', 'c'] >>> list1 [1, 'a', 3, 'b', 5, 'c', 7, 8, 9] >>> list1[slice(1,6,2)] = ['a', 'b', 'c', 'd', 'f'] # 这个方法会索引插入的区别在于:这个方法不能多插或少插 Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: attempt to assign sequence of size 5 to extended slice of size 3 查--------------------------------------------------------------------------------------------------- # [] 根据索引取值 >>> list2 = ['23', '34', '11', '77', 'aa', 'bc'] >>> list2[1] # 有返回值,返回索引对应的值,这个支持多维列表 '34' >>> list2[11] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range # [1:5:2] 根据切片来查 [1, 66, 99, 77] >>> list1 = [1,2,3,4,5,6,7,8,9] >>> list1[1:6:2] [2, 4, 6] >>> list1[slice(1,6,2)] [2, 4, 6] >>> list1[slice(5)] [1, 2, 3, 4, 5] >>> list1[slice(1,3)] [2, 3] # index()根据值取索引,返回第一个匹配到的索引,当没匹配到会报错 >>> list8 = ['a', 'a','b', 'c', 'd'] >>> list8.index('a') # 有返回值,返回匹配到的第一个索引,其查询作用,未改变列表本身 0 >>> list9 = ['a', 'a','b', 'c', 'd',['ee', 'ff']] # 注意当列表是多个维度时,里层的值是找不到的 >>> list9.index('ee') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: 'ee' is not in list # count()统计某个元素在列表中出现的次数 >>> list10 = ['12','23', '34', '34',34] >>> list10.count('34') # 有返回值,返回次数,起查询作用,未改变列表本身 2 >>> list10.count('0') # 不存在的也是可以查的,返回0 0 其他-------------------------------------------------------------------------------------------------- # copy() 复制列表,这个只针对一维列表 >>>list2 = [3, 4,'python'] >>> a = list2.copy() # 有返回值 >>> a [3, 4,'python'] # copy.deepcopy() 深浅复制,当列表是多个维度的时候,必须使用这个方法进行复制 >>> a = [1,2,['a','b'],3] >>>import copy >>>copy.deepcopy(a) # 有返回结果 [1,2,['a','b'],3] # reverse()用于反向列表中元素,注意不是倒序的意思 >>> list11 = ['Google', 'Runoob', 'Taobao', 'Baidu'] >>> list11.reverse() # 没有返回值 >>> list11 ['Baidu', 'Taobao', 'Runoob', 'Google'] # sort()用于对原列表进行排序,如果指定参数,则使用比较函数指定的比较函数。 # 注意;列表的中元素必须是同一种数值类型,否则使用该方法会报错 >>> list12 = ['23', '34', '11', '77', 'aa', 'bc'] >>> list12.sort() # 没有返回值,默认按升序排列 >>> list12 ['11', '23', '34', '77', 'aa', 'bc'] >>> list12.sort(reverse=True) # 没有返回值,设置reverse=True按降序排列 >>> list12 ['bc', 'aa', '77', '34', '23', '11'] >>> def takeSecond(elem): # 获取列表的第二个元素 ... return elem[1] >>> random = [(2, 2), (3, 4), (4, 1), (1, 3)] >>> random.sort(key=takeSecond) # key 指定可迭代对象中的一个元素来进行排序 >>> random [(4, 1), (2, 2), (1, 3), (3, 4)]
2、列表运算符
注意:列表有索引,从0开始,且列表支持截取和组合
python | 结果 | 描述 |
len([1,2,3]) | 3 | 长度 |
[1,2,3]+[4,5,6] | [1,2,3,4,5,6] | 组合 |
['HI']*4 | ['HI','HI','HI','HI'] | 重复 |
3 in [1,2,3] | True | 判断 |
for x in [1,2,3]:print x; | 1 2 3 | 迭代 |
3、列表复制
列表复制分两类:引用复制和非引用复制
引用复制:复制的是地址,修改一个list,另一个list也会跟这个修改,如下代码所示
>>> list1 = [0,1,2,3,4] >>> list2 = list1 # 这样的操作就是引用复制 >>> list2 [0, 1, 2, 3, 4] >>> id(list1) 1971146394248 >>> id(list2) # 可以发现他们的ID是一样的 1971146394248 >>> list1[2]='new' # 修改了其中一个列表,另一个也是跟着修改,因为他们只是指向了同一个地址,所以读取到地址里面的内容都是一样的 >>> list1 [0, 1, 'new', 3, 4] >>> list2 [0, 1, 'new', 3, 4]
非引用复制:这个复制方式是复制的内容,地址是不一样的,所以修改其中一个列表,另一个列表是不会被改变的,代码如下所示
>>> list_a = [1,3,4,5] >>> list_b = list_a[:] # 这个是非引用复制,复制的是内容 方式2:list_b = list_a.copy()
>>> list_b [1, 3, 4, 5] >>> id(list_a) 1971116594184 >>> id(list_b) # 它们的ID是不一样的 1971146394440 >>> list_a[1]=888 >>> list_a [1, 888, 4, 5] >>> list_b # 改变其中一个,宁一个列表不会受到影响 [1, 3, 4, 5]
4、列表推导
# 代码示例1 >>> listone = [2,3,4] >>> listtwo = [2*i for i in listone if i>2] >>> listtwo [6, 8] # 代码示例2 >>> print([m+n for m in 'ABC' for n in 'XYZ']) ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ'] # 代码示例3 >>> d = {'x':'A','y':'B','z':'C'} >>> print([k+'='+v for k,v in d.items()]) ['x=A', 'y=B', 'z=C'] # 代码示例3 >>> l = ['Hello','World','IBM','Apple'] >>> print([s.lower() for s in l]) ['hello', 'world', 'ibm', 'apple']
5、其他
迭代器、生成器、队列的实现都与列表有关,这个后面的笔记阐述
元组
注意:
-
不可变的序列,下面的修改操作不会改变本身,而是另外开辟一个空间来存储
-
元组与列表类似,不同之处在于元组的元素值不能修改,再次强调是“元素”
-
元祖的修改只有一个拼接,其他都不行
-
元祖的方法都是查询,都有返回值
- 任意无符号的对象,以逗号隔开,默认为元组
1、元组内置方法
#创建有个区别,请留意 >>>tup1 = (25) >>> type(tup1) # 不加逗号,类型为整型 <class 'int'> >>> tup1 = (20,) >>> type(tup1) # 加上逗号,类型为元组 <class 'tuple'> # 修改元祖,这里是通过拼接来修改的,并没违背元祖的值不允许修改的原则,生成的是一个新的元祖,并没有改变本身 >>> tuo1 = (1,2) >>> top2 = (3,4) >>> tuo1+top2 (1, 2, 3, 4) # index() 用于从元祖中找出某个值第一个匹配项的索引位置 >>> tup1 = (1,1,1,2,2,3) >>> tup1.index(1) 有返回值 0 # [] 通过索引来查值 >>> tuo3 = ['a', 'b', 'c'] >>> tuo3[1] 'b' # count() 统计某个元素在列表中出现的次数 >>> tup1 = [1,1,1,2,2,3] >>> tup1.count(1) 3
字符串
注意:
1、字符串内置方法
# 字符串的拼接 + >>> a = "hello" >>> b = "world" >>> a+b 'helloworld' >>> var1 = 'Hello World!' >>> var1[:6] + 'Runoob!' 'Hello Runoob!' #字符串末尾追加 += >>> a = "hello" >>> a += " world" >>> a 'hello world' #字符串重复输出 * >>> a = "hello" >>> a*2 'hellohello' #字符串的获取 [] >>> a = "hello" >>> a[0] 'h' # 字符串的截取 [ : ] 左闭右开 >>> a ="hello" >>> a[1:4] 'ell' # 判断字符串中是否有某个元素 in (not in 如果不在字符串中则返回True) >>> a ="hello" >>> 'c' in a False >>> 'e' in a True # encode 编码 语法:str.encode(encoding='UTF-8',errors='strict') errors -- 设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值。 >>> "hello".encode() b'hello' # join 将字符串列表转换字符串 >>> a = ['1', '2', '3', '4'] >>> ''.join(a) '1234' # replace 替换或者删除 >>> "hello world".replace('o', 'k') # 替换 'hellk wkrld' >>> "hello world".replace('hello', '') # 删除 ' world' # str.maketrans() 替换 和replace的区别在于:replace是按整个字串替换,而这个是对应着来替换 >>> map = str.maketrans("123", "abc") # 把前边的替换为后边的 >>> "123e 12cd".translate(map) 'abce abcd' >>> map = str.maketrans('abc','123') # 相当于a替换成1,b替换成2,c替换成3 >>> 'abweajkbkc'.translate(map) '12we1jk2k3' # expandtabs() 控制制表符的空格个数 >>> print('a\tb'.expandtabs()) # 默认是7个 a b >>> print('a\tb'.expandtabs(1)) # 控制为1个 a b >>> print('a\tb'.expandtabs(4)) # 控制为4个 a b # split 分隔字符串 默认为以所有的空字符,包括空格、换行(\n)、制表符(\t)分割等 # str.rsplit('@',1) 从末尾开始查找进行分割 >>> str = "Line1-abcdef \nLine2-abc \nLine4-abcd" >>> str.split() # 按默认进行分割 ['Line1-abcdef', 'Line2-abc', 'Line4-abcd'] >>> str.split(' ', 1 ) # 按空格分, 并分成num+1个字符串, 这里是2 ['Line1-abcdef', '\nLine2-abc \nLine4-abcd'] # strip 移除字符串头尾指定的字符(默认去掉前后的空格)或字符序列(.lstrip(), .rstrip()) >>> a = " hello world " # 默认去掉前后的空格 >>> a.strip() 'hello world' >>> b ="**hello**world**" >>> b.strip('**') # 该方法只能删除开头或是结尾的字符,不能删除中间部分的字符 'hello**world' # find 检测字符串中是否包含子字符串 str , 如果包含子字符串返回开始的索引值,否则返回-1。 >>>info = 'abca' >>> print(info.find('a')) # 从下标0开始,查找在字符串里第一个出现的子串,返回结果:0 0 >>> print(info.find('a',1)) # 从下标1开始,查找在字符串里第一个出现的子串:返回结果3 3 >>> print(info.find('3')) # 查找不到返回-1 -1 #index find()方法一样,只不过如果str不在 string中会报一个异常。 >>> info = 'abca' >>> info.index('a') 0 >>> info.index('e') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found # count 返回子字符串在字符串中出现的次数 >>> sub = "this is string example....wow!!!"; >>> sub.count('i', 4, 40) # 后面两位数是限制在哪个区间找 2 # capitalize 将字符串的第一个字母变成大写,其他字母变小写 >>> a = 'hELLO wOrld' >>> a.capitalize() 'Hello world' # lower 将所有大写字符为小写 >>> "HELLO WORLD".lower() 'hello world' # upper 将字符串中的小写字母转为大写字母 >>> "hello world".upper() 'HELLO WORLD' # title 返回"标题化"的字符串,就是说所有单词的首个字母转化为大写 >>> "hello world".title() 'Hello World' # swapcase() 把大写换成小写,小写换成大写 >>> "wecAD".swapcase() 'WECad' # endswith 判断字符串是否以指定后缀结尾 >>> a = "hello" >>> a.endswith('d') True >>> a.endswith('w', 1, 5) #限制区间 False # startswith 检查字符串是否是以指定子字符串开头 >>> a = "hello world" >>> a.startswith('he') True # isalnum() 检测字符串是否由字母、汉字和数字组成。 # isalpha() 检测字符串是否只由字母或中文组成。 # isdigit() 检测字符串是否只由数字组成 # isspace() 判断是否全部是空白字符 # islower() 检测字符串是否由小写字母组成。 # isupper() 检测字符串中所有的字母是否都为大写。 # istitle() 检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写 # 字符串的转义字符反斜杠(\) \(在行尾时) :续行符 \\ :反斜杠符号 \' :单引号 \" :双引号 \n :换行 \f :换页
2、字符串格式化和进制转换
# 进制转换
# 2 进制、8 进制、16进制 十进制:123:1*10^2+2*10^1+3*10^0 二进制:1010: 1*2^3+0*2*2+1*2^1+0*2^0 八进制: 123 : 1*8^2 + 2*8^1 +3*8^0 十六进制: FA9:15*16^2+10*16^1+9*16^0 (1,2,3,4,5,6,7,8,9,A,B,C,D,E,F) 0b123 # 表示2进制 >>> bin(11) # 从10进制计算为2进制 '0b1011' >>> int('1011',2) # 从二进制转换为10进制 11 0o123 # 表示8进制 >>> oct(11) # 把10进制转换为8进制 '0o13' >>> int('13',8) # 从八进制转换为10进制 11 0x123 # 表示16进制 >>> hex(11) # 从10进制计算为16进制 '0xb' >>> int('b',16) # 从十六进制转换为10进制 11 # 字符串补齐函数 >>> 'abc'.ljust(8, "*") #补右边 'abc*****' >>> "abc".rjust(8, '*') # 补左边 '*****abc' >>> "abc".center(8, '*') # 补中间 '**abc***' >>> 'abc'.zfill(8) # 默认在左边补0 '00000abc'
# 字符串格式化方式1:% # %s %d %f %r %e %g %s 是可以接受任意字符类型:数字、字符串都可以 >>> "%s is age %s"%('nanbei', 18) 'nanbei is age 18' >>> "string = %2s" % ('hello') # 表示长度超出2时原长度输出,小于2时,用空格左边填充 'string = hello' >>> "string = %7s" % ('hello') # 表示长度超出7时原长度输出,小于7时,用空格左边填充 'string = hello' >>> "string = %-7s" % ('hello') # 表示长度超出7时原长度输出,小于7时,用空格右边填充 'string = hello ' >>> "string = %.2s" % ('hello') # 表示长度超出2时截取2位字符,小于2时,原长度输出 'string = he' >>> "string = %.7s" % ('hello') # 表示长度超出7时截取7位字符,小于7时,原长度输出 'string = hello' 总结: #%a.bs这种格式是上面两种格式的综合,首先根据小数点后面的数b截取字符串, #当截取的字符串长度小于a时,还需要在其左侧补空格 >>> "string=%7.2s" % ("hello") 'string= he' >>> "string=%2.7s" % ('hello') 'string=hello' >>> "string=%-10.7s" % ('hello') 'string=hello ' %d 接收整型 num = 13 >>> "num=%d" % num # 原样输出 'num=13' >>> "num=%1d" % num # 表示如果小于1位,在左侧补充空格 'num=13' >>> "num=%3d" % num # 表示如果小于3位,在左侧补充空格,大于等于时,原样输出 'num= 13' >>> "num=%-3d" % num # 表示如果小于3位,在右侧补充空格,大于等于时,原样输出 'num=13 ' >>> "num=%05d" % num # 表示小于5位时,在左侧用0来补充,注意只有这种情况(左边补充0) 'num=00013' >>> "num=%.3d" % num # 当整数的位数不够3位时,在整数左侧补0 'num=013' 总结: # %5.3d是两种补齐方式的综合,当整数的位数不够3时,先在左侧补0,还是不够5位时,再在左侧补空格 # 规则就是补0优先 >>> "num=%5.3d" % num 'num= 013' #%05.3d是两种补齐方式的综合,当整数的位数不够3时,先在左侧补0,还是不够5位时,由于是05,再在左侧补0 >>> "num=%05.3d" % num 'num=00013' %f import math >>> "PI=%f" % math.pi 'PI=3.141593' # 原样输出,默认小数点后6位 >>> "PI=%9f" % math.pi # 表示打印长度9位数,小数点也占一位,不够左侧补空格 'PI= 3.141593' >>> "PI=%03.f" % math.pi # 表示去掉小数输出整数,03表示不够3位数左侧补0 'PI=003' >>> "PI=%6.3f" % math.pi # 表示小数点后面精确到3位,总长度6位数,包括小数点,不够左侧补空格 'PI= 3.142' >>> "PI=%-6.3f" % math.pi # 表示小数点后面精确到3位,总长度6位数,包括小数点,不够右侧补空格 'PI=3.142 ' %r # 是一个万能的格式,它会将后面给的参数原样打印出来 >>> "%r %r %r %r"%(1,2,3,4) '1 2 3 4' %e # 科学计数法 >>> "%e"% math.pi # 保留小数点后面六位有效数字,指数形式输出。 '3.141593e+00' >>> '%e' % 123 '1.230000e+02' >>> "%.3e"% math.pi # 保留3位小数位,使用科学计数法。 '3.142e+00' >>> '%.3e' % 123 '1.230e+02' # 字符串格式化方式2:format
>>> "my name is {}, I'm age is {}".format('南北',18)
"my name is 南北, I'm age is 18"
>>> '输出左对齐定长为10位 [{:<10}]'.format('12') # 默认填充空格的 '输出左对齐定长为10位 [12 ] >>> '输出右对齐定长为10位 [{:>10}]'.format('12') # #默认填充空格的 '输出右对齐定长为10位 [ 12]' >>> '输出右对齐定长为10位 [{:0>10}]'.format('12') '输出右对齐定长为10位 [0000000012]' #修改填充,填充只能是一个ASCII字符 >>> '输出居中对齐定长为10位,填充x [{:x^10}]'.format('12') #修改填充,填充只能是一个ASCII字符 '输出居中对齐定长为10位,填充x [xxxx12xxxx]' >>> '{:.2f}'.format(1233442.23453) #通常都是配合 f 使用,其中.2表示长度为2的精度,f表示float类型 '1233442.23' >>> '{:,}'.format(9987733498273.0432) #使用逗号金额分割符 '9,987,733,498,273.043 >>> 'test:{0:3}'.format(math.pi) # 由于输出位数大于宽度,就按实际位数输出了 'test:3.141592653589793' >>> 'test:{0:.3}'.format(math.pi) # .3 指定除小数点外的输出位数 'test:3.14'
# 字符串格式化方式3:Template
import string
>>> s = string.Template('I am a $key')
>>> s.substitute(key="boy")
'I am a boy'
>>> s2 = string.Template('My name is $kye1')
>>> s2.substitute(kye1 = name)
'My name is nanbei'
序列公共方法
# len(s) 返回: 序列中包含元素的个数 >>> list1 = ['1', 'b','c','v'] >>> len(list1) 4 # min(s)返回:序列中最小的元素 >>> tup1 = (1,22,33,4) >>> min(tup1) 1 # max(s) 返回:序列中最大的元素 >>> set1 ={2,333,4,55} >>> max(set1) 333 # all(s) 返回:True,如果所有元素都为真的话 (如果iterable的所有元素不为0、''、False、 >>> list2 = [3,2,False] >>> list1 = [1,2,0] >>> all(list1) False >>> list2 = [1,2,""] >>> all(list2) False >>> list2 = [3,2,None] >>> all(list2) False >>> list2 = [3,2,False] >>> all(list2) False # any(s) 返回:True,如果任一元素为True的话,返回True, 和all()函数的功能是相反的 >>> list = [1,2,0] >>> any(list) True