在学习什么是元组之前,我们先来看看如何创建一个元组对象:
a = ('abc',123) b = tuple(('def',456)) print a print b
使用()或者 tuple() 函数创建,不过注意这里的传参还是要用()括起来的,所以一般不用函数的方式创建,函数的作用多在于强制转换数据类型(在内置函数中说明)。
另外,当元组只有一个元素的时候:
这样写是不行的,因为函数的传参也是用(),所以解释器不知道你是要传参还是创建元组。
所以创建元组的时候尤其是只有一个元素的元祖的时候一定要加逗号。
接下来我们开始学习元组的内置方法。
按照我之前惯用的学习方法,首先还是先来 help(tuple) 看看其内置方法有哪些。
Help on class tuple in module __builtin__: class tuple(object) | tuple() -> empty tuple | tuple(iterable) -> tuple initialized from iterable's items | | If the argument is a tuple, the return value is the same object. | | Methods defined here: | | __add__(...) | x.__add__(y) <==> x+y | | __contains__(...) | x.__contains__(y) <==> y in x | | __eq__(...) | x.__eq__(y) <==> x==y | | __ge__(...) | x.__ge__(y) <==> x>=y | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __getnewargs__(...) | | __getslice__(...) | x.__getslice__(i, j) <==> x[i:j] | | Use of negative indices is not supported. | | __gt__(...) | x.__gt__(y) <==> x>y | | __hash__(...) | x.__hash__() <==> hash(x) | | __iter__(...) | x.__iter__() <==> iter(x) | | __le__(...) | x.__le__(y) <==> x<=y | | __len__(...) | x.__len__() <==> len(x) | | __lt__(...) | x.__lt__(y) <==> x<y | | __mul__(...) | x.__mul__(n) <==> x*n | | __ne__(...) | x.__ne__(y) <==> x!=y | | __repr__(...) | x.__repr__() <==> repr(x) | | __rmul__(...) | x.__rmul__(n) <==> n*x | | count(...) | T.count(value) -> integer -- return number of occurrences of value | | index(...) | T.index(value, [start, [stop]]) -> integer -- return first index of value. | Raises ValueError if the value is not present. | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T