內置函數tuple()
有助於在 python 中創建元組。元組是具有多個元素的單個變量。元組中的元素是不可變的,這意味着不能修改它。
**tuple(iterable)** #where iterable may be list, range, dict etc
元組()參數:
接受單個參數。元組元素是有序的,不可更改的,並且允許重複的值。
參數 | 描述 | 必需/可選 |
---|---|---|
可迭代的 | 可列舉的(列表、範圍等)。)或迭代器對象 | 可選擇的 |
元組()返回值
如果 iterable 沒有傳遞給tuple()
,該函數將創建一個空的 tuple 並返回一個 TypeError。
| 投入 | 返回值 |
| 如果可迭代 | 元組 |
Python 中tuple()
方法的示例
示例 1:如何使用tuple()
創建元組
tuple1 = tuple()
print('tuple1 =', tuple1)
# creating a tuple from a list
tuple2 = tuple([2, 3, 5])
print('tuple2 =', tuple2)
# creating a tuple from a string
tuple1 = tuple('Python')
print('tuple1 =',tuple1)
# creating a tuple from a dictionary
tuple1 = tuple({2: 'one', 4: 'two'})
print('tuple1 =',tuple1)
輸出:
tuple1 = ()
tuple2 = (2, 3, 5)
tuple1 = ('P', 'y', 't', 'h', 'o', 'n')
tuple1 = (2, 4)
示例 2:用元組()演示類型錯誤的程序
# Error when a non-iterable is passed
tuple1 = tuple(1)
print(tuple1)
輸出:
Traceback (most recent call last):
File "/home/eaf759787ade3942e8b9b436d6c60ab3.py", line 5, in
tuple1=tuple(1)
TypeError: 'int' object is not iterable
原創文章,作者:WCU9A,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/129346.html