序列操作符 |
作用 |
seq[ind] |
获得下标为ind的元素 |
seq[ind1:ind2] |
获得下标从ind1到ind2间的元素集合 |
seq * expr |
序列重复expr次 |
seq1 + seq2 |
链接序列seq1和seq2 |
obj in seq |
判断obj元素是否包含在seq中 |
obj not in seq |
判断obj元素是否不包含在seq中 |
用来判断一个元素是否属于一个序列:
>>> "h" in "hello owrld" True >>> 1 in (2, 3, 4) False
>>> "hello " + "world" 'hello world' >>> arr = [] >>> arr.append("hello ") >>> arr.append("world") >>> "".join(arr) 'hello world' >>> num1 = [1, 2] >>> num2 = [3, 4] >>> num1.extend(num2) >>> num1 [1, 2, 3, 4]
>>> ss = "hello world" >>> ss[:] 'hello world' >>> ss[1:4] 'ell' >>> ss[:-1] 'hello worl' >>> ss[::2] 'hlowrd'
函数 |
含义 |
list(iter) |
把可迭代对象转换为列表 |
str(obj) |
把obj对象转换成字符串(对象的字符串表示法) |
unicode(obj) |
把对象转换成unicode字符串 |
basestring() |
抽象工厂函数,为str和unicode函数提供父类 |
tuple(iter) |
把一个可迭代对象转换成一个元组对象 |
函数名 |
功能 |
enumerate(iter) |
接受一个可迭代对象作为参数,返回一个enumerate对象 |
len(seq) |
返回seq的长度 |
max(iter,key=None) or max(arg0,...) |
返回iter或(arg0,..)的最大值,如果指定key,则key必须是可传给sort()方法,用来比较的回调函数 |
min(iter,key=None) or min(arg0,...) |
返回最小值 |
reversed(seq) |
接受一个序列作为参数,返回一个以逆序访问的迭代器 |
sorted(iter, func=None,key=None,reverse=False) |
接受一个可迭代对象作为参数,返回一个有序的列表 |
sum(seq, init=0) |
返回seq和可选参数init的总和,等同于reduce(operator.add, seq, init) |
zip([it0, it1,..]) |
返回一个列表(具体含义看实例) |
实例如下:
>>> num = [1, 2, 3, 4] >>> enumerate(num) <enumerate object at 0x0000000003EB6AB0> >>> list(enumerate(num)) [(0, 1), (1, 2), (2, 3), (3, 4)] >>> len(num) 4 >>> max(num) 4 >>> min(num) 1 >>> reversed(num) <list_reverseiterator object at 0x00000000035A0160> >>> list(reversed(num)) [4, 3, 2, 1] >>> sorted(num) [1, 2, 3, 4] >>> sum(num) 10 >>> zip(num) <zip object at 0x00000000035713C8> >>> list(zip(num)) [(1,), (2,), (3,), (4,)]
列表能保留任意数目的python对象的灵活容器.
>>> aList = [] >>> aList.append(1) >>> id(aList) 65662280 >>> aList.append(2) >>> id(aList) 65662280 >>> aList.extend([3, 4, 5]) >>> aList [1, 2, 3, 4, 5] >>> aList.append(["hello", "world"]) >>> aList [1, 2, 3, 4, 5, ['hello', 'world']] >>> aList[5][1] 'world' >>> aList[2] = "what" >>> aList [1, 2, 'what', 4, 5, ['hello', 'world']] >>> del aList[1] >>> aList [1, 'what', 4, 5, ['hello', 'world']] >>> aList.remove("what") >>> aList [1, 4, 5, ['hello', 'world']] >>> del aList >>> aList Traceback (most recent call last): File "<pyshell#203>", line 1, in <module> aList NameError: name 'aList' is not defined
元组是不可变类型,所以通常可以用作一个字典的key.
在创建一个元组时要注意一点:只有一个元素的元组需要在元组分隔符里面加一个逗号(,)以防止跟普通的分组操作符混淆.
>>> aTuple = (123, "abc", 3.45, ["inner", "tuple"], 8-9j) >>> aTuple[1:5] ('abc', 3.45, ['inner', 'tuple'], (8-9j)) >>> id(aTuple) 65420808 >>> bTuple = aTuple + (1,2,3) >>> bTuple (123, 'abc', 3.45, ['inner', 'tuple'], (8-9j), 1, 2, 3) >>> id(bTuple) 65625672 >>> del aTuple >>> id(aTuple) Traceback (most recent call last): File "<pyshell#211>", line 1, in <module> id(aTuple) NameError: name 'aTuple' is not defined
对象赋值实际上是简单的对象引用,也就是说,当你创建一个对象,然后把它赋给另一个变量的时候,python并没有拷贝这个对象,而是拷贝了这个对象的引用.
实例如下:
>>> person = ["name", ["savings", 100.00]] >>> hubby = person[:] >>> wifey = list(person) >>> [id(x) for x in (person,hubby,wifey)] [65794568, 65794440, 65735944]假设hubby取走50元,则会影响到wifey的账户:
>>> hubby[0] = "joe" >>> wifey[0] = "jane" >>> hubby, wifey (['joe', ['savings', 100.0]], ['jane', ['savings', 100.0]]) >>> hubby[1][1] = 50.00 >>> hubby, wifey (['joe', ['savings', 50.0]], ['jane', ['savings', 50.0]])原因是我们仅仅做了一次浅拷贝.对一个对象进行浅拷贝其实是新建了一个类型跟原对象一样,其内容是原来对象的引用,换句话说,这个拷贝的对象本身是新的,但是它的内容不是.序列类型对象的浅拷贝是默认类型拷贝,并可以以下几种方式实施:1.完全切片操作[:],2利用工厂函数(list,dict),3使用copy模块的copy函数.
我们可以使用深拷贝来实现hubby和wifey的账户独立:
>>> person = ["name", ["savings", 100.00]] >>> hubby = person >>> import copy >>> wifey = copy.deepcopy(person) >>> [id(x) for x in (person, hubby, wifey)] [55781320, 55781320, 65735496] >>> hubby[0] = "joe" >>> wifey[0] = "jane" >>> hubby, wifey (['joe', ['savings', 100.0]], ['jane', ['savings', 100.0]]) >>> hubby[1][1] = 50.00 >>> hubby, wifey (['joe', ['savings', 50.0]], ['jane', ['savings', 100.0]])
实际上可以通过id进行查看:
>>> person = ["name", ["savings", 100.00]] >>> hubby = person[:] >>> wifey = list(person) >>> [id(x) for x in (person, hubby, wifey)] [50112776, 60091528, 60092104] >>> [id(y) for x in (person, hubby, wifey) for y in x] [14821560, 60091208, 14821560, 60091208, 14821560, 60091208] >>> hubby1 = person[:] >>> import copy >>> wifey = copy.deepcopy(person) >>> [id(y) for x in (person, hubby, wifey) for y in x] [14821560, 60091208, 14821560, 60091208, 14821560, 60091848]
创建:
>>> dict1 = {} >>> dict2 = {"name" : "earth", "port" : 80} >>> dict3 = dict((["x", 1], ["y", 2])) >>> dict4 = {}.fromkeys(("x", "y"), -1) >>> dict1 {} >>> dict2 {'name': 'earth', 'port': 80} >>> dict3 {'y': 2, 'x': 1} >>> dict4 {'y': -1, 'x': -1}dict()为工厂函数,要求参数为一元组/列表,且元组/列表的元素必须可迭代.而fromkeys()用来创建一个"默认"字典,字典中元素具有相同的值.
访问:
>>> for key in dict2: print("key=%s,value=%s" % (key, dict2[key])) key=name,value=earth key=port,value=80 >>> for key, value in dict2.items(): print("key=%s,value=%s" % (key, value)) key=name,value=earth key=port,value=80而我们可以使用in或者has_key()(备注:在最新版本python中,好像没有此方法)来判断是否有其键值:
>>> "name" in dict2 True >>> "server" in dict2 False更新和删除:
>>> dict2["name"] = "hello" >>> dict2 {'name': 'hello', 'port': 80} >>> del dict2["name"] >>> dict2 {'port': 80} >>> dict2.clear() >>> dict2 {} >>> del dict2 >>> dict2 Traceback (most recent call last): File "<pyshell#271>", line 1, in <module> dict2 NameError: name 'dict2' is not defined
dict():
dict()工厂函数被用来创建字典,如果不提供参数,会生成空字典.当容器类型对象作为一个参数传递给方法dict()时,如果参数是可以迭代的,即一个序列,或是一个迭代器,或是一个支持迭代的对象,那每个可迭代的元素必须成对出现.在每个值对中,第一个元素是字典的键,第二个元素是字典中的值:
>>> dict(zip(("x", "y"), (1, 2))) {'y': 2, 'x': 1} >>> dict([["x", 1], ("y", 2)]) {'y': 2, 'x': 1}如果输入参数是一个映射对象,对其调用dict()会从存在的字典里复制内容来生成新的字典.新生成的字典是原来字典对象的浅复制版本,与调用copy一样.
>>> import copy >>> dict1 = {"x" : 1, "y" : 2} >>> dict2 = dict1.copy() >>> dict1 {'y': 2, 'x': 1} >>> dict2 {'x': 1, 'y': 2} >>> id(dict1) 65373640 >>> id(dict2) 65791112hash():
hash()可以判断某个对象是否可以做一个字典的键.将一个对象作为参数传递给hash(),会返回这个对象的哈希值.只有这个对象是可哈希的,才可作为字典的键:
>>> hash("hello") 5758210612334034391 >>> hash([]) Traceback (most recent call last): File "<pyshell#286>", line 1, in <module> hash([]) TypeError: unhashable type: 'list'
update():
将一个字典的内容添加到另一个字典中:
>>> dict2 = {"host" : "earth", "port" : 80} >>> dict3 = {"host" : "venus", "server" : "http"} >>> dict2.update(dict3) >>> dict2 {'host': 'venus', 'port': 80, 'server': 'http'} >>> dict3.clear() >>> dict3 {}
字典的键,不允许一个键对应多个值:
>>> dict1 = {"foo" : 789, "foo" : "xyz"} >>> dict1 {'foo': 'xyz'}而且,键必须是可哈希的,所以只能使用数值,字符串和元素值必须为数值/字符串的元组.
集合对象是一组无序排列的可哈希的值,有两种不同类型:可变集合和不可变集合.可变集合不是可哈希,所以既不能用作字典的键也不能做其他集合中的元素.而不可变集合刚好相反.
创建:
>>> s = set("cheeseshop") >>> t = frozenset("bookshop") >>> s {'o', 'h', 'p', 'e', 's', 'c'} >>> t frozenset({'o', 'h', 'p', 's', 'b', 'k'})访问
无法通过索引来访问:
>>> s[1] Traceback (most recent call last): File "<pyshell#300>", line 1, in <module> s[1] TypeError: 'set' object does not support indexing >>> for i in s: print(i) o h p e s c更新:
>>> s.add("z") >>> s.update("pypi") >>> s.remove("o") >>> >>> s {'h', 'p', 'e', 's', 'c', 'y', 'i', 'z'} >>> s -= set("pypi") >>> s {'h', 'e', 's', 'c', 'z'} >>> t.add("z") Traceback (most recent call last): File "<pyshell#311>", line 1, in <module> t.add("z") AttributeError: 'frozenset' object has no attribute 'add'删除:
>>> del s >>> s Traceback (most recent call last): File "<pyshell#313>", line 1, in <module> s NameError: name 's' is not defined