當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python tuple()用法及代碼示例

tuple() 內置函數可用於在 Python 中創建元組。

在 Python 中,元組是不可變的序列類型。創建元組的方法之一是使用tuple() 構造。

用法:

tuple(iterable)

參數:

  • iterable(可選)- 可迭代的(列表、範圍等)或迭代器對象

如果 iterable 未傳遞給 tuple() ,則該函數返回一個空元組。

示例:使用 tuple() 創建元組

t1 = tuple()
print('t1 =', t1)

# creating a tuple from a list
t2 = tuple([1, 4, 6])
print('t2 =', t2)

# creating a tuple from a string
t1 = tuple('Python')
print('t1 =',t1)

# creating a tuple from a dictionary
t1 = tuple({1: 'one', 2: 'two'})
print('t1 =',t1)

輸出

t1 = ()
t2 = (1, 4, 6)
t1 = ('P', 'y', 't', 'h', 'o', 'n')
t1 = (1, 2)

相關用法


注:本文由純淨天空篩選整理自 Python tuple()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。