英文文檔: 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 containe ...
英文文檔:
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)