本文共 11525 字,大约阅读时间需要 38 分钟。
列表及常用操作
列表是一个序列,用于顺序的存储数据。
定义与初始化
lst = list() #使用list函数定义空列表
lst = [] #使用中括好定义空列表
lst = [1,2,3,4]#使用中括号定义带初始值的列表
lst = list(range(1,10))#使用list函数把可迭代对象转化为列表。
注意:通常在定义列表的时候,使用中括号,在转化可迭代对象为列表时用list函数。
访问列表元素
1.通过下标访问,下标是从零开始。
2.当下标超出范围时,会抛出indexerror。
3.负数索引从右边开始,索引从-1开始。
4.负数索引超出范围,也会抛出indexerror。
通过value查找索引
lst = [1,2,3,4,5,6]
In:lst.index(3)
Out:2
语法:
L.index(value, [start, [stop]])list = [1,2,3,2,4,3,5]
###################
list.index(2) index方法返回查找的第一个索引
1
###########################
list.index(2,2)从第二个索引后查找2 start参数指定从哪个索引开始查找
3
list.index(3,2) 从第二个索引开始查找3
2
##########################
list.index(2,2,3) #end参数指定到哪个索引结束,并且不包含该索引,当值不存在该范围时,会抛出ValueError
###########################
list.index(2,0,3) 索引0到3的的值(2)的索引是1
1
########################
list.index(2,-4,-1)#start 和stop参数可以为负数,但是从左往右查找
3
########################
语法:
def index(lst, value, start=0, stop=-1):
i = start
for x in lst[start: stop]:
if x == value:
return i
i += 1
raise ValueError
##################################
count方法返回值在列表里出现的次数
list.count(3)
2
list.count(2)
2
list.count(2)
0
####################
语法:
def count(list,value):
c = 0
for x in list:
if x == value:
c += 1
return c
#########################
总结:
1.通过索引访问元素
2.index方法根据值返回第一个索引
3.count方法返回元素在列表里的个数
4.index和count的时间复杂度是O(n),线性复杂度,效率与数据规模线性相关。
5.凡是stop比start小,总是抛出ValueError
list元素的修改
list = [1,2,3,2,4,3,5]
list[2]
3
list[3]
2
list[3] = 5 修改列表的元素直接使用下标操作取出元素并对其赋值。
返回的list 为[1,2,3,5,4,3,5]
注意:修改元素有且只有一种方法。对超出范围得到索引修改元素,会抛出IndexError
eg:list[7] = 7
list增加元素(无法使用索引来操作)
语法:help(lst.append)
append(...)
L.append(object) -- append object to end
lst.append(9)
lst
[1, 2, 5, 2, 4, 3, 7, 9]
append原地修改lst,返回结果是None
########################
help(lst.insert)
insert(...)
L.insert(index, object) -- insert object before index
lst.insert(2,10)
lst
[1, 2, 10, 5, 2, 4, 3, 7, 9]
lst.insert(1,'a')
lst
[1, 'a', 2, 10, 5, 2, 4, 3, 7, 9]
insert也是原地修改list,返回结果是None
lst.insert(12,9)
lst.insert(100,8)
lst.insert(-100,'e')
lst
['e', 1, 'a', 2, 10, 5, 2, 4, 3, 7, 9, 9, 8]
注意:insert当索引超出范围时
索引是负数,会在第0个元素前插入,索引是整数,会在最后一个元素后插入。
append的时间复杂度是O(1)常数时间,效率和数据的规模无关,
insert的时间复杂度是O(n)线性时间,效率和数据规模线性相关。
######################################
extend(...)
L.extend(iterable) -- extend list by appending elements from the iterable
lst.extend([1,2,3])
lst
[6, 'e', 1, 'a', 2, 10, 5, 2, 4, 3, 7, 9, 9, 8, 1, 2, 3]
lst.extend(range(2,7))
lst
[6, 'e', 1, 'a', 2, 10, 5, 2, 4, 3, 7, 9, 9, 8, 1, 2, 3, 2, 3, 4, 5, 6]
注意:原地修改,返回None。
append操作的是单个元素。
extend操作的是可迭代对象。
lst = list(range(5))
lst
[0, 1, 2, 3, 4]
lst + ['a','b','c']
[0, 1, 2, 3, 4, 'a', 'b', 'c']
lst
[0, 1, 2, 3, 4]
注意:不修改list本身,返回一个新的list,list的连续操作。
list的删除
remove(...)
L.remove(value) -- remove first occurrence of value.
Raises ValueError if the value is not present.
lst = [1,2,3,2,4,3,5,3,4]
lst.remove(1)#原地修改,返回None,根据值删除元素。
lst
[2, 3, 2, 4, 3, 5, 3, 4]
lst.remove(2)#从左到右删除第一个
lst
[3, 2, 4, 3, 5, 3, 4]
lst.remove(10)#当值不存在是抛出ValueError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
pop(...)
L.pop([index]) -> item -- remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
lst.pop()#返回并删除最后一个元素
4
lst
[3, 2, 4, 3, 5, 3]
lst.pop(1)#返回并删除索引所在位置的元素
2
lst
[3, 4, 3, 5, 3]
lst.pop(100)#当删除的索引不存在时,会抛出IndexError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: pop index out of range
lst.clear()#删除所有元素
注意:pop不传递index参数时间复杂度是O(1)
POP传递index参数时间复杂度是O(n)
pop根据索引删除元素,并且返回删除的元素
remove根据值删除元素,返回值为None
其他操作
求list的长度
反转
lst = list(range(4))
lst
[0, 1, 2, 3]
lst.reverse()#原地修改,返回None,翻转列表
lst
[3, 2, 1, 0]
排序
lst = []
lst = [3,1,2,4,5,7,3,2]
lst
[3, 1, 2, 4, 5, 7, 3, 2]
lst.sort()#原地修改,返回None
lst
[1, 2, 2, 3, 3, 4, 5, 7]
lst.sort(reverse=True)
lst
[7, 5, 4, 3, 3, 2, 2, 1]
复制
lst = []
lst = list(range(3))
lst
[0, 1, 2]
lst2 = lst
lst2
[0, 1, 2]
lst2[1] = 5
lst2
[0, 5, 2]
lst
[0, 5, 2]
复制操作是引用是传递。也叫浅拷贝
copy方法
lst = [0,1,2]
lst2 = lst.copy()#影子拷贝
lst2[1] = 5
lst2
[0,5,2]
lst
[0,1,2]
赋值操作对可变对象是引用传递,对不可变对象是值传递
lst = [1,[1,2,3],2]
lst
[1,[1,2,3],2]
lst2 = lst.copy
lst2[1][1] = 5
lst2
[1,[1,5,3],2]
lst
[1,[1,5,3],2]
def copy(lst):
tmp = []
for i in range(lst):
tmp.append(i)
return tmp
深拷贝
import copy
lst2 = copy.deepcopy(lst)
lst2
[1,[1,5,3],2]
lst2[1][1] = 7
lst2
[1,[1,7,3],2]
lst
[1,[1,5,2],2]
######################
字符串极其操作 (字符串是一个集合类型并不是基本类型)
四种定义字符串的方法
s = 'hello,world'
s = "hello,world"
s = '''hello,world'''
s = """hello,world"""
其中,前两种完全一样,后两种完全一样。
s = '''hello,python
i like python'''s
'hello,python\ni like python'
说明:三引号(单引号)可以定义多行字符串
s = 'hello,python
i like python'File "", line 1 s = 'hello,python ^SyntaxError: EOL while scanning string literal
注意:单/双引号只能定义单行字符串
字符串的转义
s = 'i like \npython'
print(s)
i like python
s = 'i\'m summer'
s
"i'm summer"
path = 'C:\\windows\\\\nt\\system32'
path = r'C:\windows\nt\system32'#加r前缀代表此字符串是自然字符串,不会转义
print(path)
C:\windows\nt\system32
\n
print('123\n456')
123456
\r
print('123\r456')
456
字符串的下标操作
s = 'i\'m summer'
s[1]
i
s[2]
" '"
s[3]
" "
s[4] = 'c'#字符串是不可变的
eg:
TypeError: 'str' object does not support item assignment
字符串是可迭代对象
for c in s:
print(c)
1'm summer
同时字符串也可以转换为list
list(s)
['1', "'", 'm', ' ', 's', 'u', 'm', 'm', 'e', 'r']s.count('m')3
join操作,只有是字符串才可以join.
lst = ['i','sm','summer']
' '.join(lst)#join是字符串的方法,参数是内容为字符串的可迭代对象,接收者是分隔符
'i sm summer'
','.join(lst)
'i,sm,summer'
#字符串的分割操作
s.split
rsplit
splitlines
s = 'i love python'
s
'i love python'
s.split()#默认使用空格分割,
['i', 'love', 'python']
' i love python'.split()#多个空格当成一个空格处理
['i', 'love', 'python']'i love python'.split( ' ')#当指定了以空格为分隔符时,每个空格都处理['i', '', '', '', '', '', 'love', 'python']s.split(maxsplit=1)['i', 'love python']'i i i i i i i i i i'.split(maxsplit=2)#split从左往右分割字符串,maxsplit参数表示分割多少次,默认值为-1,表示分割所有分割符['i', 'i', 'i i i i i i i i']
'i love python'.split('o')
['i l', 've pyth', 'n']
'i love python'.split('lo')#分割符可以是任意的字符
['i ', 've python']
rsplit是split从右往左的版本
'i i i i i i '.rsplit(maxsplit=1)
['i i i i i', 'i']
'i i i i i i'.split()
['i', 'i', 'i', 'i', 'i', 'i']'i i i i i i '.rsplit()['i', 'i', 'i', 'i', 'i', 'i']注意:当不是用maxsplit参数时,split和rsplit的表现形式是一样的,但是split的效率高于rsplits.splitlines()s.splitlines()#按行分割,并且返回结果不带操作符['i am summer', 'i love python']s.splitlines(True)#按行分割,并且返回结果带换行符['i am summer\n', 'i love python']help(str.partition)partition(...) S.partition(sep) -> (head, sep, tail) Search for the separator sep in S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return S and two empty strings. 'i am summer'.partition(' ')#总是返回一个三元组,它按传入的分割符分割一次,得到head ,tail,返回结果 是head,sep,tail ('i', ' ', 'am summer') 注意: rpartition 是partition从右往左的版本 cfg = 'mysql.connect=mysql://user:passwd@127.0.0.1:3307/test' cfg.partition('=') ('mysql.connect', '=', 'mysql://user:passwd@127.0.0.1:3307/test')cfg = 'env=PATH=/usr/bin:$PATH' cfg.partition('=') ('env', '=', 'PATH=/usr/bin:$PATH') ' '.partition('=')(' ', '', '') cfg.split('=')['env', 'PATH', '/usr/bin:$PATH']解释:def partition(s,sep): if s =='': return '','','' tmp = s.split(sep,maxsplit) if len(tmp) == 2: return tmp[0],sep,tmp[1] if len(tmp) == 1: return tmp[0],'',''字符串大小写转换和排版s = 'test's.upper()'TEST' s.upper().lower() 'test' s.title()'Test''i love python'.title()#每个单词首字符大写'I Love Python's.capitalize()'Test''i love python'.capitalize()#句子首字母大写'I love python's.center(7)' test 's.zfill(8)'0000test's.casefold()#统一转换为大写,或者统一转换为小写,在不同的平台下有不同的表现形式,但是在同一平台下,表现形式相同,通常用来忽略大小写时的比较'test''Test TTest'.casefold()'test ttest''\t'.expandtabs(4)' '字符串的修改s.replaces.strips.lstrips.rstrips.ljusts.rjusts = 'i love python's.replace('love','give up')#replace返回一个新的字符串,使用new替换old'i give up python's = 'i very very love python's.replace('very','not')#有多少个替换多少个'i not not love python's.replace('very','not',1)#可选的count参数,指定替换多少次'i not very love python'help(str.strip)strip(...) S.strip([chars]) -> str Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead.s = ' hahahah hahahah 's.strip()#strip用来移除字符串前后的空格'hahahah hahahah's = '\n \r \t hahaha hahaha \t \n \r's.strip()#strip移除字符串前后的空白'hahaha hahaha's = '####haha ## haha ###'s.strip('#')#可以指定移除的字符'haha ## haha 's = '{ { haha haha }}'s.strip('{}')#可以指定移除多个字符' haha haha '
s.lstrip('{}')#lstrip表现和strip一样。但是只处理左端
' hahha haha}}'s.rstrip('{}')#rstrip表现和strip一样,但是只处理右端
'{ { hahha haha's = 'test's.ljust(10)#ljust原字符串在左边'test 's.rjust(10)#rjust原字符串在左边' test's.center(10)#原字符串在中间' test 's.center(10,'#')#可以指定填充字符'###test###'s.ljust(10,'#')'test######'s.center(10,'##')#填充字符串长度只能为1TypeError: The fill character must be exactly one character longs.center(3)#如果宽度小于等于原字符串长度,不做任何操作'test's.center的左边优先级高于右边字符串的查找* s.find* s.index* s.count* s.rfind* s.rindexs = 'i love python's.find('love')#从左往右查找,找到第一个子串love 返回子串首字母的索引2s.find('love1')#当子串不存在的时候,返回-1-1s = 'i very very love python's.find('very')2s.find('very',3)#start参数可以指定从哪里开始查找7s.find('very',3,5)#end参数指定到哪里结束,end不包含-1s.find('very',3,11)7s.rfind('very')#rfind是find的从右往左的版本7s.rfind('very',8)#start和stop意义一样,是先根据start和stop截取字符串,再查找。索引总是从左往右-1help(s.index)index(...) method of builtins.str instance S.index(sub[, start[, end]]) -> int Like S.find() but raise ValueError when the substring is not found.s.index('very')2s.index('very',3)7s.index('very',8)#index查找当子串不存在时,抛出valueerrorValueError: substring not founds.find('very',8)#find查找,子串不存在时返回-1-1s.rindex('very')#rindex时index从右往左的版本7s.count('very')2s.count('haha')0s.count('very',3)1list(enumerate(s))[(0, 'i'), (1, ' '), (2, 'v'), (3, 'e'), (4, 'r'), (5, 'y'), (6, ' '), (7, 'v'), (8, 'e'), (9, 'r'), (10, 'y'), (11, ' '), (12, 'l'), (13, 'o'), (14, 'v'), (15, 'e'), (16, ' '), (17, 'p'), (18, 'y'), (19, 't'), (20, 'h'), (21, 'o'), (22, 'n')]字符串的判断* s.startswith* s.endswith* s.is*s.startswith('i very')#判断字符串是否以某个前缀开始,返回结果是bool类型Trues.startswith('abc')Falses.startswith('very',2)#start参数表示的是从索引start处开始比较,返回值是bool类型
Trues.startswith('very',2,5)#end表示从索引end处停止比较Falses.endswith('python')#判断字符串是否以某个后缀结尾,返回bool类型Trues.endswith('python',17)#start参数表示从索引start处开始比较Trues.endswith('python',0,22)#end参数表示到索引end为止,不包含endFalsehelp(s.isalnum)isalnum(...) method of builtins.str instance S.isalnum() -> bool Return True if all characters in S are alphanumeric and there is at least one character in S, False otherwise.s.isalnum()False'a'.isalnum()True合法的标识符是字母或者下划线开头,仅包含字母数字和下划线'a'.isidentifier()True'27'.isidentifier()False'class'.isidentifier()True字符串的格式化是拼接字符串的一种手段1.''.join(['i', 'love', 'python'])2.'i' + 'love' +'python'返回结果:'ilovepython' join 和 + 难以控制格式printf style 字符串格式化 从c语言继承过来的s ='i love %s' #待格式化的字符串,当一个字符串存在占位符的时候,占位符:%加一个格式控制符s % ('python',)#传入参数顺序的替换占位符,返回替换后的字符串,原串不变。'i love python''i love %s,i am %d'%('python',18)'i love python,i am 18'
'i love %s,i am %d'%('python',)#占位符个数和参数个数不匹配的时候,会抛出typeError
s = 'i love %s,i am %d'
s % ('python',18 )
'i love python,i am 18's % ('python','18')#当类型不匹配时,会抛出TypeErrors % (18,18)#当占位符是%s,其实隐式调用了str() %r隐式调用了'i love 18,i am 18'练习:s = 'i love %s , i am %s , i am %d' % ('python','summer',19)print(s)i love python , i am summer , i am 19字符串原样输出:print('%s %%d' % 'haha')haha %dprintf style 格式化对从其他语言,尤其是c语言转过来的,容易接受,但是Python所推荐的方法s = 'i love {}'format方法使用大括号作为占位符
。。。。。。。。。