Python內建函數(64)——tuple,python內建64tuple
英文文檔:
The constructor builds a tuple whose items are the same and in the same order as iterable‘s items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a tuple, it is returned unchanged. For example, tuple('abc') returns ('a', 'b', 'c') and tuple( [1, 2, 3] ) returns (1, 2, 3). If no argument is given, the constructor creates a new empty tuple, ().
說明:
1. 函數功能建立一個新的元組。
2. 不傳入任何參數函數將建立一個空的元組。
#不傳入參數,建立空元組>>> tuple() ()
3. 函數可以接收1個可迭代對象作為參數,將使用可迭代對象的每個元素建立一個新的元組。
#傳入不可迭代對象,不能建立新的元組>>> tuple(121)Traceback (most recent call last): File "<pyshell#17>", line 1, in <module> tuple(121)TypeError: 'int' object is not iterable#傳入可迭代對象。使用其元素建立新的元組>>> tuple('121')('1', '2', '1')>>> tuple([1,2,1])(1, 2, 1)>>> tuple((1,2,1))(1, 2, 1)
4. 建立新的元組還可以使用一對括弧的方式:
4.1 使用一對括弧來建立空的元組。
>>> a= ()>>> a()
4.2 建立單個元素的元組時必須尾隨逗號。
>>> a = (1,)>>> a #a是元組(1,)>>> a = (1)>>> a #a是數值1
4.3 建立多個元素的元組,依次用逗號隔開。
>>> a = (1,2,3)>>> a(1, 2, 3)