元组是存放任意元素集合,不能修改其内容.
简单创建元组
In [1]: T = () #创建一个空的元组
In [2]: T
Out[2]: ()
In [3]: T = tuple() #创建一个空的元组
In [4]: T
Out[4]: ()
In [8]: T = (1,) #创建包含一个对象的元组,不能写成T = (1),这会被解释成T = 1
In [9]: T
Out[9]: (1,)
In [10]: T = (1,2,3) #可以这样写
In [11]: T
Out[11]: (1, 2, 3)
In [12]: T = 1,2,3,4,5 #也可以这样写
In [13]: T
Out[13]: (1, 2, 3, 4, 5)
两个变量复制
In [1]: a,b = 1,2
In [2]: a
Out[2]: 1
In [3]: b
Out[3]: 2
注意,a和b都不是元组类型,(a,b)才是元组类型
python的多元赋值原理是tuple的元组封装 (tuple packing) 和 序列拆封(sequence unpacking)
因此交换两个变量可以不需要临时变量,例如
In [4]: a,b = b,a
In [5]: a
Out[5]: 2
In [6]: b
Out[6]: 1
还可以这样写
In [17]: a,*b = 1,2,3
In [18]: a
Out[18]: 1
In [19]: b
Out[19]: [2, 3]
注意,a和b都不是元组类型,(a,b)才是元组类型。
通过help(tuple)查看列表的属性及方法。
>>> help(tuple)
Help on class tuple in module builtins:
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__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(...)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self
|
| __mul__(self, value, /)
| Return self*value.n
|
| __ne__(self, value, /)
| Return self!=value.
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return self*value.
|
| 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.
下面分别来解析:
tuple() -> empty tuple 创建一个空的元组
In [1]: T = tuple()
In [2]: T.__len__() #可以调用元组的各种方法
Out[2]: 0
tuple(iterable) -> tuple initialized from iterable's items
If the argument is a tuple, the return value is the same object.
将可迭代器里的对象初始化为元组。如果参数是元组,则返回同一对象
In [3]: s = "123"
In [4]: T = tuple(s)
In [5]: T
Out[5]: ('1', '2', '3')
In [6]: s #s本身不会改变
Out[6]: '123'
In [15]: t = tuple((1,2))
In [16]: t
Out[16]: (1, 2)
| __add__(self, value, /)
| Return self+value.
| 元组相加,返回元组
In [1]: T = (1,2)
In [2]: T.__add__((3,4))
Out[2]: (1, 2, 3, 4)
In [3]: T.__add__(3) #参数必须是元组,否则报错
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in ()
----> 1 T.__add__(3)
TypeError: can only concatenate tuple (not "int") to tuple
| __contains__(self, key, /)
| Return key in self. 判断是否存在某对象
In [1]: T = 1,2,'abc',[2,3]
In [2]: T.__contains__(1)
Out[2]: True
In [3]: T.__contains__([2,3])
Out[3]: True
In [4]: T.__contains__([2])
Out[4]: False
相当于使用in
In [5]: 1 in T
Out[5]: True
In [6]: [2,3] in T
Out[6]: True
In [7]: [2] in T
Out[7]: False
| __eq__(self, value, /)
| Return self==value. 判断元组与对象是否相等
In [1]: T = 1,2,'abc',[2,3]
In [2]: T.__eq__(5) #参数不是元组不能比较,但也不报错
Out[2]: NotImplemented
In [3]: T.__eq__((5,6)) #参数是元组可以比较是否相等
Out[3]: False
In [4]: T.__eq__([5,6]) #参数不是元组不能比较,但也不报错
Out[4]: NotImplemented
| __ge__(self, value, /)
| Return self>=value. 判断元组不小于某对象 与 __eq__类似
| __getattribute__(self, name, /)
| Return getattr(self, name). 获取属性。
In [5]: T.__getattribute__('__gt__') __gt__ 是T的属性
Out[5]:
In [6]: T.__getattribute__('gt') gt不是T的属性,报错
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
in ()
----> 1 T.__getattribute__('gt')
AttributeError: 'tuple' object has no attribute 'gt'
| __getitem__(self, key, /)
| Return self[key]. #获取索引值所对于的对象
In [7]: T = 1,2,'abc',[2,3]
In [8]: T.__getitem__(2) #获取该元组的第二个对象
Out[8]: 'abc'
In [9]: T[2]
Out[9]: 'abc'
In [10]: T[6] #越界报错
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
in ()
----> 1 T[6]
IndexError: tuple index out of range
In [11]: T[-1] #获取该元组的最后一个对象
Out[11]: [2, 3]
__getnewargs__(...)
In [17]: t = T.__getnewargs__()
In [18]: type(t)
Out[18]: tuple
In [19]: t
Out[19]: ((1, 2, 'abc', [2, 3]),)
In [20]: len(t)
Out[20]: 1
In [21]: help(T.__getnewargs__)
Help on built-in function __getnewargs__:
__getnewargs__(...) method of builtins.tuple instance
| __gt__(self, value, /)
| Return self>value. 判断元组大于某对象 与 __eq__类似
| __hash__(self, /)
| Return hash(self).
In [22]: T = (1,2,3)
In [23]: T.__hash__()
Out[23]: -378539185
In [24]: hash(T)
Out[24]: -378539185
hash(object)Return the hash value of the object (if it has one). Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup. Numeric values that compare equal have the same hash value (even if they are of different types, as is the case for 1 and 1.0).
| __iter__(self, /)
| Implement iter(self). 可迭代器对象
In [25]: T = (1,2,'3')
In [26]: T.__iter__()
Out[26]:
In [27]: for i in T.__iter__():
...: print (i)
...:
1
2
3
| __le__(self, value, /)
| Return self<=value. 判断元组不大于某对象 与 __eq__类似
| __len__(self, /)
| Return len(self). 返回元组长度,即元素个数
In [28]: T = (1,2,'abcdef',[2,3])
In [29]: T.__len__()
Out[29]: 4
In [30]: len(T)
Out[30]: 4
| __lt__(self, value, /)
| Return self
| __mul__(self, value, /)
| Return self*value.n
In [31]: T = (1,2,'3')
In [32]: T.__mul__(2)
Out[32]: (1, 2, '3', 1, 2, '3')
In [34]: T.__mul__([2])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in ()
----> 1 T.__mul__([2])
TypeError: 'list' object cannot be interpreted as an integer
| __ne__(self, value, /)
| Return self!=value. 判断元组不等于某对象 与 __eq__类似
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
创建并返回一个新的tuple对象
| __repr__(self, /)
| Return repr(self). 与repr功能相同
In [1]: T = (1,2,'3')
In [2]: T.__repr__()
Out[2]: "(1, 2, '3')"
In [3]: type(T.__repr__())
Out[3]: str
| __rmul__(self, value, /)
| Return self*value.
In [4]: T
Out[4]: (1, 2, '3')
In [5]: T.__rmul__(5)
Out[5]: (1, 2, '3', 1, 2, '3', 1, 2, '3', 1, 2, '3', 1, 2, '3')
In [6]: T.__rmul__('5')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in ()
----> 1 T.__rmul__('5')
TypeError: 'str' object cannot be interpreted as an integer
| count(...)
| T.count(value) -> integer -- return number of occurrences of value
返回元组中某对象的个数。
In [1]: T = (1,2,1,1,2,2,3,'3',[4,5])
In [2]: T.count(1)
Out[2]: 3
In [3]: T.count(2)
Out[3]: 3
In [4]: T.count(3)
Out[4]: 1
In [5]: T.count('3')
Out[5]: 1
In [6]: T.count('4')
Out[6]: 0
index(...)
| T.index(value, [start, [stop]]) -> integer -- return first index of value.
| Raises ValueError if the value is not present.
In [12]: T
Out[12]: (1, 2, 1, 1, 2, 2, 3, '3', [4, 5])
In [13]: T.index(1) #返回第一个出现对象的位置
Out[13]: 0
In [14]: T.index('3') #返回第一个出现对象的位置
Out[14]: 7
In [15]: T.index(0) #元组中不存在是时报错
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
in ()
----> 1 T.index(0)
ValueError: tuple.index(x): x not in tuple