Python 內(nèi)建函數(shù)列表 > Python 的內(nèi)置函數(shù) tuple
Python 的內(nèi)置函數(shù) tuple() 用于創(chuàng)建一個(gè)不可變的序列(元組)。以下是關(guān)于 tuple() 函數(shù)的詳細(xì)說(shuō)明:
功能描述
tuple() 函數(shù)可以將可迭代對(duì)象(如列表、字符串、集合等)轉(zhuǎn)換為元組。如果調(diào)用時(shí)不傳入?yún)?shù),則返回一個(gè)空元組。
語(yǔ)法
tuple(iterable)
-
iterable(可選):任何可迭代對(duì)象(如列表、字符串、字典等)。如果未提供,則返回空元組
()。
返回值
返回一個(gè)包含輸入可迭代對(duì)象元素的元組。元組是不可變的,創(chuàng)建后不能修改。
示例
-
從列表創(chuàng)建元組:
list_data = [1, 2, 3] tuple_data = tuple(list_data) print(tuple_data) # 輸出:(1, 2, 3) -
從字符串創(chuàng)建元組:
string_data = "hello" tuple_data = tuple(string_data) print(tuple_data) # 輸出:('h', 'e', 'l', 'l', 'o') -
從字典創(chuàng)建元組(默認(rèn)轉(zhuǎn)換為鍵的元組):
dict_data = {'a': 1, 'b': 2} tuple_data = tuple(dict_data) print(tuple_data) # 輸出:('a', 'b') -
空元組:
empty_tuple = tuple() print(empty_tuple) # 輸出:() -
從集合創(chuàng)建元組:
set_data = {1, 2, 3} tuple_data = tuple(set_data) print(tuple_data) # 輸出:(1, 2, 3)(順序可能不同)
注意事項(xiàng)
- 元組是不可變的,創(chuàng)建后無(wú)法修改其內(nèi)容(如添加、刪除或更改元素)。
- 如果傳入不可迭代的對(duì)象(如整數(shù)、布爾值等),會(huì)拋出
TypeError。 - 元組比列表更輕量,適合存儲(chǔ)不需要修改的數(shù)據(jù)。
應(yīng)用場(chǎng)景
- 存儲(chǔ)固定數(shù)據(jù)(如配置項(xiàng)、常量集合)。
- 作為字典的鍵(因?yàn)樵M是不可變的,而列表不能作為字典的鍵)。
- 函數(shù)返回多個(gè)值時(shí)(實(shí)際上返回的是一個(gè)元組)。
效率說(shuō)明
元組的創(chuàng)建和訪問(wèn)速度比列表快,適合用于大量數(shù)據(jù)的只讀場(chǎng)景。