在 Python 中將列表和元組相互轉換:list()、tuple()

商業

當您想在 Python 中將列表(數組)和元組相互轉換時,請使用 list() 和 tuple()。

如果將諸如集合類型以及列表和元組之類的可迭代對像作為參數給出,則返回列表和元組類型的新對象。

以下列表、元組和範圍類型變量是示例。

l = [0, 1, 2]
print(l)
print(type(l))
# [0, 1, 2]
# <class 'list'>

t = ('one', 'two', 'three')
print(t)
print(type(t))
# ('one', 'two', 'three')
# <class 'tuple'>

r = range(10)
print(r)
print(type(r))
# range(0, 10)
# <class 'range'>

range() 從 Python 3 返回一個範圍類型的對象。

請注意,雖然為了方便使用了術語“轉換”,但實際上是創建了新對象,而原始對象保持不變。

生成列表:list()

當一個可迭代對象(如元組)被指定為 list() 的參數時,會生成一個包含該元素的列表。

tl = list(t)
print(tl)
print(type(tl))
# ['one', 'two', 'three']
# <class 'list'>

rl = list(r)
print(rl)
print(type(rl))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# <class 'list'>

生成元組:tuple()

當一個可迭代對象(例如列表)被指定為 tuple() 的參數時,將生成一個具有該元素的元組。

lt = tuple(l)
print(lt)
print(type(lt))
# (0, 1, 2)
# <class 'tuple'>

rt = tuple(r)
print(rt)
print(type(rt))
# (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
# <class 'tuple'>

添加或更改元組的元素

元組是不可變的(不可更新),因此不能更改或刪除元素。但是,可以通過 list() 製作列表,更改或刪除元素,然後再次使用 tuple() 來獲得元素更改或刪除的元組。

Copied title and URL