Python核心数据类型之序列类型及其运算(列表、元组运算及其拷贝)
序列:序列表示索引为非负整数的有序对象集合,包括字符串、列表和元组,所有序列都支持迭代;
序列类型:
字符串(strings):字符串也属于序列类型,不可变类型;
字符串字面量:把文本放入单引号、双引号或三引号中;''', """
如果要使用unicode编码,则在字符之前使用字符u进行标识,如u"fieldyang"
文档字串:模块、类或函数的第一条语句是一个字符的话,该字符串就成为文档字符串,可以使用__doc__属性引用;
列表:(list),可变类型,使用[]创建,如['My','name','is','Field'],支持插入、删除和替换元素;
元组:(tuple),不可变类型,使用()创建,如("one","two")
注意:列表和元组均不真正存储数据,而是存放对象应用
例1:字符串使用unicode编码
In [44]: str1=u"hello world"
In [45]: type(str1)
Out[45]: Unicode
例2:文档字串引用
In [46]: def printName():
....: "Function Test!"
....: print "hellofieldyang!"
....:
In [47]: printName()
hello fieldyang!
In [48]: printName.__doc__
Out[48]: 'Function Test!'
序列通用操作:
运算符:
索引运算符:[i]
切片运算符:[i:j]
扩展切片符:[i:j:stride]
所有序列都支持的操作和方法:
s[i]
s[i:j]
s[i:j:stride]
len(s)
min(s)
max(s)
sum(s)
all(s):检查s中的所有项是否为true
any(s):检查s中的任意项是否为true
s1+ s2: 连接
s1* N: 重复
objin s1: 成员关系判断
objnot in s1:
支持操作:
常用对象的自有的方法:
str1.capitalize():首字母大写
str1.isupper():是否为大写
str1.index(x, {,start [, stop]}):返回指定字符串索引范围中x首次出现的位置,否则报错
str1.join(t):使用str1作为分隔符连接序列t中字符串
str1.count():计数
str1.lower():转换为小写形式
str1.islower():是否为小写
str1.split([sep [,maxreplace]]):使用sep作为分隔符划分,maxreplace为最大划分次数
str1.upper():转换为大写形式
str1.replace(old, new [,maxreplace]):替换一个子字符串
例1:序列运算符的应用
[root@test ~]# ipython
In [1]: str1 = 'www.field.com'
In [2]: str1[2:]
Out[2]: 'w.field.com'
In [3]: str1[0:6]
Out[3]: 'www.fi'
In [4]: str1[0:8:2]
Out[4]: 'wwfe'
In [5]: str1[8:0:-1]
Out[5]: 'dleif.ww'
In [6]: str1[0]
Out[6]: 'w'
In [7]: len(str1)
Out[7]: 13
In [8]: str1[-2]
Out[8]: 'o'
In [9]: str1[-3:]
Out[9]: 'com'
In [10]: str1[-3::-1]
Out[10]: 'c.dleif.www'
In [11]: str1[-3:2:-1]
Out[11]: 'c.dleif.'
例2:序列常见操作和方法
In [12]: max(str1)
Out[12]: 'w'
In [13]: min(str1)
Out[13]: '.'
In [14]: l1=[1,2,3,4,5]
In [15]: sum(l1)
Out[15]: 15
In [16]: print str1
www.field.com
In [17]: all(str1)
Out[17]: True
例3:字符对象内置方法的使用
In [18]: str1.
str1.capitalize str1.format str1.isupper str1.rindex str1.strip
str1.center str1.index str1.join str1.rjust str1.swapcase
str1.count str1.isalnum str1.ljust str1.rpartition str1.title
str1.decode str1.isalpha str1.lower str1.rsplit str1.translate
str1.encode str1.isdigit str1.lstrip str1.rstrip str1.upper
str1.endswith str1.islower str1.partition str1.split str1.zfill
str1.expandtabs str1.isspace str1.replace str1.splitlines
str1.find str1.istitle str1.rfind str1.startswith
In [18]: str1.islower()
Out[18]: True
In [19]: str1.upper()
Out[19]: 'WWW.FIELD.COM'
In [20]: str1.isupper()
Out[20]: False
In [21]: str1.capitalize()
Out[21]: 'Www.field.com'
In [22]: str1.index('i')
Out[22]: 5
In [24]: str1.index('w',2)
Out[24]: 2
In [25]: str1.index('w')
Out[25]: 0
In [26]: str1.index('w',2,5)
Out[26]: 2
In [27]: l2=list(str1)
In [28]: print l2
['w', 'w', 'w', '.', 'f', 'i', 'e', 'l','d', '.', 'c', 'o', 'm']
In [29]: ''.join(l2)
Out[29]: 'www.field.com'
In [30]: str1.replace('field','FIELD')
Out[30]: 'www.FIELD.com'
In [31]: str1.replace('m','M')
Out[31]: 'www.field.coM'
In [32]: str1.split(str1)
Out[32]: ['', '']
In [33]: str1.split('.')
Out[33]: ['www', 'field', 'com']
In [34]: str1.split('e')
Out[34]: ['www.fi', 'ld.com']
In [35]: str2 = " hello "
In [36]: print str2
hello
In [37]: str2.strip()
Out[37]: 'hello'
In [38]: str2.strip('')
Out[38]: ' hello '
In [39]: str2.strip('o')
Out[39]: ' hello '
In [40]: str2 = " hello"
In [41]: str2.strip('o')
Out[41]: ' hell'
序列类型及其支持的操作和方法
1)、列表
其为容器类型,任意对象的有序集合。可以通过索引访问其中的元素,是可变对象,其长度可变且支持异构,即任意嵌套
例1:列表的构建及使用
In [1]: l1 = []
In [2]: print l1
[]
In [3]: id(l1)
Out[3]: 18293032
In [4]: l2 = [1,2,3,4,5]
In [5]: print l2
[1, 2, 3, 4, 5]
In [6]: l3 = [1,'b',['x','y'],('w','z')]
In [7]: print l3
[1, 'b', ['x', 'y'], ('w', 'z')]
列表修改、内容删除
列表支持在原处修改,可以修改指定的索引元素,也可以修改指定的分片,内置删除语句
s[i] = v :项目赋值
s[1:j] = t :切片赋值
s[i:j:stride] = t :扩展切片赋值
del s[i] :删除项目
del s[1:j] :删除切片
del s[i:j:stride] :删除扩展切片
例2:列表对象修改及删除
In [8]: print l2
[1, 2, 3, 4, 5]
In [9]: l2[2] = 'sss'
In [10]: print l2
[1, 2, 'sss', 4, 5]
In [11]: l2[1:3]
Out[11]: [2, 'sss']
In [12]: l2[1:3] = []
In [13]: print l2
[1, 4, 5]
In [14]: del l2[1]
In [15]: print l2
[1, 5]
In [16]: del l2[0:]
In [17]: print l2
[]
In [18]: l3 = [1,2,3,4,5,6]
列表内置方法:
list(l):将l转换为一个列表
l.append(x):将一个新元素x追加到列表末尾
l.extend(t):将一个新列表t追加到列表末尾
l.insert(i,x):在索引i处插入x,必须为整型
l.remove(x):移除列表中x元素
l.sort():正向排序
l.count(x):计算列表中x出现次数
l.index(x, {,start [, stop]}):返回列表索引范围中x的位置索引
l.pop([i]):返回元素i并移除,i省略时移除最后一个元素
l.reverse():逆序排序
列表解析:[]
例3:列表内置方法使用示例
In [19]: l3.
l3.append l3.extend l3.insert l3.remove l3.sort
l3.count l3.index l3.pop l3.reverse
In [19]: l3.append('www')
In [20]: print l3
[1, 2, 3, 4, 5, 6, 'www']
In [21]: id(l3)
Out[21]: 18311792
In [22]: l3.append('666')
In [23]: id(l3)
Out[23]: 18311792
In [24]: l4 = ['a','b','c']
In [25]: l3.append(l4)
In [26]: id(l3)
Out[26]: 18311792
In [27]: print l3
[1, 2, 3, 4, 5, 6, 'www', '666', ['a', 'b','c']]
In [28]: l3.count(2)
Out[28]: 1
In [29]: l3.count(6)
Out[29]: 1
In [31]: l3.extend(l4)
In [32]: print l3
[1, 2, 3, 4, 5, 6, 'www', '666', ['a', 'b','c'], 'a', 'b', 'c']
In [33]: id(l3)
Out[33]: 18311792
In [34]: l3.index('www')
Out[34]: 6
In [35]: l3.insert(6,888)
In [36]: print l3
[1, 2, 3, 4, 5, 6, 888, 'www', '666', ['a','b', 'c'], 'a', 'b', 'c']
In [39]: l3.pop()
Out[39]: 'c'
In [40]: l3.pop()
Out[40]: 'b'
In [41]: l3.pop()
Out[41]: 'a'
In [42]: l3.pop()
Out[42]: ['a', 'b', 'c']
In [43]: print l3
[1, 2, 3, 4, 5, 6, 888, 'www', '666']
In [44]: l3.remove(3)
In [45]: print l3
[1, 2, 4, 5, 6, 888, 'www', '666']
In [46]: l3.reverse()
In [47]: print l3
['666', 'www', 888, 6, 5, 4, 2, 1]
In [48]: l3.sort()
In [49]: print l3
[1, 2, 4, 5, 6, 888, '666', 'www']
列表间操作:
l1 + l2: 合并两个列表,返回一个新的列表;不会修改原列表;
l1 * N: 把l1重复N次,返回一个新列表;
in: 成员关系判断字符, 用法 obj incontainer
not in: obj not in container
例4:列表间操作示例
In [50]: str1 = 'hello'
In [51]: str2 = 'field'
In [53]: str1+str2
Out[53]: 'hellofield'
In [54]: str1 * 3
Out[54]: 'hellohellohello'
In [56]: l1 = [1,2,3]
In [57]: l1 * 3
Out[57]: [1, 2, 3, 1, 2, 3, 1, 2, 3]
In [58]: 2 in l1
Out[58]: True
In [59]: 22 in l1
Out[59]: False
In [60]: range(10)
Out[60]:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
列表复制:
深浅复制都是对源对象的复制,占用不同的内存空间;如果源对象只有一级目录的话,源做任何改动,不影响深浅复制对象;如果源对象不止一级目录的话,源做任何改动,都要影响浅复制,但不影响深复制。
列表复制方式:
变量复制:l2 = l1,引用同一对象
import copy
深复制:拷贝所有对象,顶级对象及其嵌套对象。包括:父级对象及其子对象
l2 = copy.deepcopy(l1)
浅复制:只拷贝顶级的对象,即只包括:父级对象
切片复制:l2 = l1[:]
l2 = copy.copy(l1)
例5:列表的复制
In [68]: l1 = [1,2,3]
In [69]: id(l1)
Out[69]: 18311576
In [70]: l2 = l1
In [71]: id(l2)
Out[71]: 18311576
#“=”复制只是使用不同变量名引用同意对象,id不变
In [72]: l1.append(4)
In [73]: print l2
[1, 2, 3, 4]
In [74]: id(l2)
Out[74]: 18311576
In [75]: l3 = l1[:]
# “切片”复制只是复制顶级的对象,相当于浅复制(copy.copy),父级元素改变,源数据不变,其父级元素的内层元素改变,源数据会改变,id会改变
In [76]: id(l3)
Out[76]: 19455224
In [77]: print l3
[1, 2, 3, 4]
In [78]: l1.append(5)
In [79]: print l3
[1, 2, 3, 4]
In [80]: print l1
[1, 2, 3, 4, 5]
In [81]: import copy
In [82]: id(l1)
Out[82]: 18311576
In [83]: l5 = copy.deepcopy(l1)
#深复制,复制一个容器对象,以及它里面的所有元素(包含元素的子元素),内置的任一元素改变均不会影响源数据。
In [84]: id(l5)
Out[84]: 16402480
In [85]: copy.
copy.Error copy.deepcopy copy.name
copy.PyStringMap copy.dispatch_table copy.t
copy.copy copy.error copy.weakref
2)、元组:(tuple)
不可变类型,使用()创建,如("one","two")
表达式符号:()
容器类型:任意对象的有序集合,通过索引访问其中的元素,不可变对象,长度固定,支持异构和嵌套
常见操作:
()
(1,)
(1,2)
t1 + t2:
t1 * N:
in:
not in:
虽然元组本身不可变,但如果元组内嵌套了可变类型的元素,那么此类元素的修改不会返回新元组;
例1:元组创建及方法使用
In [1]: t1=(1,2,2,3,4,7,7,7)
In [2]: t1.
t1.count t1.index
In [2]: t1.count(2)
Out[2]: 2
In [3]: t1.count(7)
Out[3]: 3
In [4]: t1.index(7)
Out[4]: 5
In [5]: 7 in t1
Out[5]: True
In [6]: 77 in t1
Out[6]: False
In [7]: print t1
(1, 2, 2, 3, 4, 7, 7, 7)
In [8]: print t1[2:]
(2, 3, 4, 7, 7, 7)
In [9]: len(t1)
Out[9]: 8
In [10]: t2 = 'a','b','c'
In [11]: print t2
('a', 'b', 'c')
例2:元组间操作
In [12]: t1+t2
Out[12]: (1, 2, 2, 3, 4, 7, 7, 7, 'a', 'b','c')
In [13]: t1 * 3
Out[13]: (1, 2, 2, 3, 4, 7, 7, 7, 1, 2, 2,3, 4, 7, 7, 7, 1, 2, 2, 3, 4, 7, 7, 7)
In [14]: 'a' in t2
Out[14]: True
In [15]: 1 in t2
Out[15]: False
In [16]: 1 not in t2
Out[16]: True
In [22]: id(t3)
Out[22]: 140455260108832
In [23]: t3[2].append(6)
In [24]: print t3
(1, 2, [3, 4, 6])
In [25]: id(t3)
Out[25]: 140455260108832