python-序列类型
所谓序列类型就是系列中的每一个元素都是有编号的,其中第一个元素的编号(即索引)为0,第二个元素的编号为1,以此类推(相反最后一个元素的变化为-1,倒数第二个元素的编号为-2)。python中的序列有:列表(list),字符串(str),元组(tuple)。最大值,最小值,长度,索引,切片,相加,相乘和序列元素检查这些操作都适用于序列类型,python还提供一些内置函数,对于操作序列非常方便。
1.序列的通用操作
1)最大值和最小值
python提供的内置函数max,min非常有用,min和max分别返回系列中最小的元素和最大的元素。
1 >>> nums = [23, 34, 12, 56] 2 >>> max(nums) 3 56 4 >>> min(nums) 5 12
2)长度
python提供内置函数len可以返回序列中元素的个数。
1 >>> len(nums) 2 4
3)索引
序列中所有的元素都有一个编号(即从0开始,依次递增),例如,我们创建一个字符串’hello_python‘,字符串中索引1指向的元素是’2‘。
View Code
python 还可以使用负数索引,从左往右(即从最后一个元素开始),-1指向最后一个元素
View Code4)切片
在python我们可以使用切片的方式来访问序列中特定范围内的元素。
View Code前面的切片我们取到的是索引区间中的所有元素,因为我们忽略了另一个参数(即步长)。默认情况下,步长的值为1,如果我们吧步长设置为2或3呢。
View Code5)序列乘法
python中只要将序列乘以一个数n,就是创建一个重复原先序列n次的新序列。
View Code6)序列加法
python中我们可以使用加法运算符(+)来拼接序列。但是不同的序列间的加法python不支持。
View Code7)序列元素检查
python提供运算符in,来检查序列中是否包含某个特定元素,如果包含元素则返回True,反之返回False。
View Code2.列表
1)修改列表元素的值
python可以直接通过索引获取列表的元素,并且直接用‘=’赋予新的值
1 >>> l = [1,2,3,4,5] 2 >>> l[3] = 9 3 >>> l 4 [1, 2, 3, 9, 5]
2)删除元素
使用del 语句就可以将列表中的元素轻松删除
1 >>> l = [1,2,3,4,5] 2 >>> del l[2] 3 >>> l 4 [1, 2, 4, 5]
3)给切片赋值
1 >>> l = [1,2,3,4,5] 2 >>> l[1:3] = [0,0] 3 >>> l 4 [1, 0, 0, 4, 5] 5 #给切片赋值,列表长度更长了 6 >>> l = [1,2,3,4,5] 7 >>> l[1:3] = [9,9,9] 8 >>> l 9 [1, 9, 9, 9, 4, 5]
4)列表方法
1 class list(object): 2 """ 3 list() -> new empty list 4 list(iterable) -> new list initialized from iterable's items 5 """ 6 def append(self, p_object): 7 # real signature unknown; restored from __doc__ 8 """ L.append(object) -> None -- append object to end """ 9 pass 10 11 def clear(self): 12 # real signature unknown; restored from __doc__ 13 """ L.clear() -> None -- remove all items from L """ 14 pass 15 16 def copy(self): 17 # real signature unknown; restored from __doc__ 18 """ L.copy() -> list -- a shallow copy of L """ 19 return [] 20 21 def count(self, value): 22 # real signature unknown; restored from __doc__ 23 """ L.count(value) -> integer -- return number of occurrences of value """ 24 return 0 25 26 def extend(self, iterable): 27 # real signature unknown; restored from __doc__ 28 """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """ 29 pass 30 31 def index(self, value, start=None, stop=None): 32 # real signature unknown; restored from __doc__ 33 """ 34 L.index(value, [start, [stop]]) -> integer -- return first index of value. 35 Raises ValueError if the value is not present. 36 """ 37 return 0 38 39 def insert(self, index, p_object): 40 # real signature unknown; restored from __doc__ 41 """ L.insert(index, object) -- insert object before index """ 42 pass 43 44 def pop(self, index=None): 45 # real signature unknown; restored from __doc__ 46 """ 47 L.pop([index]) -> item -- remove and return item at index (default last). 48 Raises IndexError if list is empty or index is out of range. 49 """ 50 pass 51 52 def remove(self, value): 53 # real signature unknown; restored from __doc__ 54 """ 55 L.remove(value) -> None -- remove first occurrence of value. 56 Raises ValueError if the value is not present. 57 """ 58 pass 59 60 def reverse(self): 61 # real signature unknown; restored from __doc__ 62 """ L.reverse() -- reverse *IN PLACE* """ 63 pass 64 65 def sort(self, key=None, reverse=False): 66 # real signature unknown; restored from __doc__ 67 """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """ 68 pass
1.append(self, p_object)
append方法用于将一个对象附加到列表的末尾(直接修改列表,而不是创建一个新的列表)。
#append方法需要我们传入一个对象作为参数(def append(self, p_object))
>>> l = ['python', 'c', 'c++']
>>> l.append('java')
>>> l
['python', 'c', 'c++', 'java']
2.clear(self)
clear方法的作用就是清空列表
1 #直接调用clear方法就可以情况列表,无需传入参数 2 >>> l = ['python', 'c', 'c++'] 3 >>> l.clear() 4 >>> l 5 []
3.copy(self)
copy方法就是复制列表,这里的复制浅复制。与赋值跟深复制存在区别。copy方法的效果与前面讲的通用方法中的切片list[:]的效果类似
1 >>> l = ['python', 'c', 'c++', [1,2,3]] 2 >>> lst = l.copy() 3 >>> lst 4 ['python', 'c', 'c++', [1, 2, 3]] 5 >>> lst = l[:] 6 >>> lst 7 ['python', 'c', 'c++', [1, 2, 3]]
4.count(self, value)
count方法的作用是计算列表中特定元素在列表中出现的次数
1 #count需要我们传入一个value作为参数,最后将返回value在列表中出现的次数(def count(self, value))
2 >>> l = ['python', 'c', 'c++', 'python', 'java', 'java', 'python', 'c']
3 >>> l.count('python')
4 3
5 >>> l.count('c')
6 2
5.extend(self, iterable)
用于扩展列表,前面的append方法只能添加一个元素到列表的末尾,而extend方法只需传入一个可迭代对象便可以添加多个元素到列表末尾(可以用一个列表扩展当前列表,也可以用元组,字符串,字典等)
1 #extend方法需要我们传入一个可迭代对象作为参数,extend会依次迭代出对象的元素添加到列表的末尾(def extend(self, iterable))。
2 >>> l = ['python', 'c', 'c++']
3 >>> l.extend(['java', 'php'])
4 >>> l
5 ['python', 'c', 'c++', 'java', 'php']
6 >>> l.extend('china')
7 >>> l
8 ['python', 'c', 'c++', 'java', 'php', 'c', 'h', 'i', 'n', 'a']
9 #注意:当传入的是字典时,添加到列表的是字典的值
10 >>> l.extend({'name': 'lin', 'age': 18})
11 >>> l
12 ['python', 'c', 'c++', 'java', 'php', 'c', 'h', 'i', 'n', 'a', 'name', 'age']
6.index(self, value, start=None, stop=None)
index方法可以在列表中找到指定元素在列表中第一次出现的索引。
1 #index方法需要我们传入一个value作为参数,当参数存在时,返回第一次出现的索引
2 >>> l = ['python', 'c', 'c++', 'java', 'c', 'python', 'c']
3 >>> l.index('c')
4 1
5 >>> l.index('python')
6 0
7 #注意:当value不在列表中的时,程序将报错
8 >>> l.index('php')
9 Traceback (most recent call last):
10 File "<stdin>", line 1, in <module>
11 ValueError: 'php' is not in list
12
13 #index方法我们还可以传入第二个参数(开始查找的索引),第三个参数(查找结束的索引)(def index(self, value, start=None, stop=None))
14 >>> l = ['python', 'c', 'c++', 'java', 'c', 'python', 'c']
15 >>> l.index('c', 2, 5)
16 4
7.insert(self, index, p_object)
insert方法可以将一个随想插入列表,与append方法不同的是,insert可以在列表中的任何位置插入一个对象。
#insert需要我们传入两个参数,第一个参数为要插入索引位置,第二个参数是要插入的对象(def insert(self, index, p_object)) >>> l = ['python', 'c', 'c++'] >>> l.insert(2, 'java') >>> l ['python', 'c', 'java', 'c++'] #插入的是一个元素,并没有迭代 >>> l.insert(2, ['go', 'java']) >>> l ['java', 'python', ['go', 'java'], 'c', 'java', 'c++']
8.pop(self, index=None)
pop方法将删除列表中最后一个元素,并返回这个元素。如果传入一个索引值,将删除所以位该值的元素而不是最后一个原素。
1 >>> l = ['python', 'c', 'c++', 'java'] 2 >>> l.pop() 3 'java' 4 #pop方法我们还可以传入一个数,可指定删除索引为该数的元素,并返回这个元素,如果这个数大于等于列表的长度,将会报错(def pop(self, index=None)) 5 >>> l = ['python', 'c', 'c++', 'java'] 6 >>> l.pop(2) 7 'c++' 8 >>> l.pop(8) 9 Traceback (most recent call last): 10 File "<stdin>", line 1, in <module> 11 IndexError: pop index out of range
9.remove(self, value)
remove方法可以根据特定元素的值来删除列表中一个该元素
1 #传入'c',只删除列表中第一个'c'元素(def remove(self, value))
2 >>> l = ['python', 'c', 'c++', 'java', 'c', 'python', 'c']
3 >>> l.remove('c')
4 >>> l
5 ['python', 'c++', 'java', 'c', 'python', 'c']
6 #当该值不在列表中时,程序报错
7 >>> l.remove('go')
8 Traceback (most recent call last):
9 File "<stdin>", line 1, in <module>
10 ValueError: list.remove(x): x not in list
10.reverse(self)
reverse方法将返回相反顺序的列表,直接修改原列表
1 >>> l = ['python', 'c', 'c++', 'java'] 2 >>> l.reverse() 3 >>> l 4 ['java', 'c++', 'c', 'python']
11.sort(self, key=None, reverse=False)
sort方法会对列表进行排序,直接修改原列表
1 #def sort(self, key=None, reverse=False) 2 >>> l = ['python', 'c', 'c++', 'java'] 3 >>> l.sort() 4 >>> l 5 ['c', 'c++', 'java', 'python'] 6 #我们可以传入可选参数reverse,当为True的时候,以相反的顺序排列 7 >>> l.sort(reverse = True) 8 >>> l 9 ['python', 'java', 'c++', 'c'] 10 #我看可以传入可选参数key(key可以可以设置为内置函数),这里我们设置为len函数,列表便按照元素的长度来排列 11 >>> l.sort(key = len, reverse = True) 12 >>> l 13 ['python', 'java', 'c++', 'c']
3.字符串
1.center(self, width, fillchar=None)
center方法可以设置字符串长度,添加的字符默认是空格,让字符串居中。返回的是居中后的副本,并不改变原字符串
1 #center方法需要我们传入一个参数 2 >>> s = 'python' 3 >>> s.center(15) 4 ' python ' 5 #我们还可以穿日第二个参数'*', 添加部分就用center填充 6 >>> s.center(15, '*') 7 '*****python****' 8 #原字符串没有发生改变 9 >>> s 10 'python'
2.count(self, sub, start=None, end=None)
count方法返回字符串中某一特定子串出现的次数。
1 >>> s = 'pythonpython'
2 >>> s.count('o')
3 2
3.endswith(self, suffix, start=None, end=None) 和 startswith(self, prefix, start=None, end=None)
endswith和startswith分别返回字符串是否是以某子串结束和开始。
1 >>> s = 'python'
2 >>> s.startswith('py')
3 True
4 >>> s.startswith('y')
5 False
6 >>> s.endswith('on')
7 True
8 >>> s.endswith('o')
9 False
3.find(self, sub, start=None, end=None)
find方法可以在在字符串中查找字串,类似于序列的index方法,返回子串在子串中第一次出现的索引,如果不存在就返回-1。
1 >>> s = 'python' * 3
2 >>> s
3 'pythonpythonpython'
4 #这里我们传入'th',find方法返回'th'在字符串中第一次出现的索引
5 >>> s.find('th')
6 2
7 #当传入的字符串不是s的子串的时候,返回-1
8 >>> s.find('pth')
9 -1
10 #我们还可以传入第二个参数开始查找的索引位置,第三个参数结束查找的位置
11 >>> s.find('on', 5, 15)
12 10
4.join(self, iterable)与 split(self, chars=None)
join和split方法子字符串方法中非常重要的两个,join可以合并序列的元素,split的作用与join相反,拆分字符串。
1 >>> l = [1, 2, 3, 4]
2 >>> s = '+'
3 #合并的序列必须是字符串,不然程序就会报如下的错误
4 >>> s.join(l)
5 Traceback (most recent call last):
6 File "<stdin>", line 1, in <module>
7 TypeError: sequence item 0: expected str instance, int found
8 >>> l = ['p', 'y', 't', 'h', 'o', 'n']
9 >>> ''.join(l)
10 'python'
11 >>> '+'.join(l)
12 'p+y+t+h+o+n'
13 #字符串s根据空格分裂成一个列表
14 >>> s = 'hello python world'
15 >>> s.split(' ')
16 ['hello', 'python', 'world']
5.lowe(self), upper(self) 和 title(self)
lower方法返回字符串的小写版本,upper方法返回字符串的大写版本, title返回字符串的标题形式。原字符穿没有被重新赋值
1 >>> s = 'Python' 2 #字符串字母全为小写 3 >>> s.lower() 4 'python' 5 #字符串字母全为大写 6 >>> s.upper() 7 'PYTHON' 8 #原字符串没有发生改变 9 >>> s 10 'Python' 11 >>> s = 'pYthon' 12 #字符串变为标题形式(首字母大写,其他小写) 13 >>> s.title() 14 'Python' 15 #原字符串不变 16 >>> s 17 'pYthon'
6.replace(self, old, new, count=None)
replace方法将制定子串替换为另一个字符串,并且返回替换后的结果
1 #def replace(self, old, new, count=None),这边我们必须传入第一个参数旧的子串,第二个参数新的字符串。第三个参数为可选参数(默认为旧的子串出现的次数)
2 >>> s = 'hello python python python world'
3 >>> s.replace('python', 'java')
4 'hello java java java world'
5 #传入第三个参数为2时,replace就修改前两个Python
6 >>> s.replace('python', 'java', 2)
7 'hello java java python world'
8 #传入第三个参数为2时,replace就修改第一个Python
9 >>> s.replace('python', 'java', 1)
10 'hello java python python world'
7,.strip(self, chars=None),lstrip(self, chars=None),rstrip(self, chars=None)
strip方法将可以将字符串开头和结尾的空白处删除(不包括字符串中的字符串),返回删除后的结果。
lstrip则是删除字符串左边的空白处,rstrip是删除字符串右边的空白处。
1 >>> s = ' hello python world ' 2 >>> s.strip() 3 'hello python world' 4 >>> s.lstrip() 5 'hello python world ' 6 >>> s.rstrip() 7 ' hello python world'
8.translate(self, table)
translate方法与replace方法类似,都是替换字符串的一部分,但是replace只能替换字符串中某一特定子串,translace方法能同事替换多个子串
不过在替换之前我们需使用maketrans方法创建一个转换表(translate接收两个长度相同参数)
1 >>> table = str.maketrans('on', '**')
2 >>> s = 'hello python python python world'
3 #这里只有是o,n都被替换成*
4 >>> s.translate(table)
5 'hell* pyth** pyth** pyth** w*rld'
9.字符串的其他方法
|
4.元组
元组与列表类似,列表使用[ ],而元组则是使用()。还有一个差别是元组是不可修改的
1 #元组的元素间需要有一个逗号隔开,如下的代码,2后面没加逗号就是数字2,当我们加上逗号就变成了元组 2 >>> 2 3 2 4 >>> 2, 5 (2,) 6 #元组支持count(self, value)方法,计算元组中指定元素的个数 7 >>> tu = (1,2,3,4,5,3,4,5,2,2) 8 >>> tu.count(2) 9 3 10 #元组也支持index(self, value, start=None, stop=None)方法,返回指定元素在元组中第一次出现的索引 11 >>> tu.index(2) 12 1 13 当元素不在元组里是,报错 14 >>> tu.index(9) 15 Traceback (most recent call last): 16 File "<stdin>", line 1, in <module> 17 ValueError: tuple.index(x): x not in tuple


浙公网安备 33010602011771号