在Python中,創(chuàng)建元組非常簡單。元組是一種不可變的序列類型,這意味著一旦創(chuàng)建了元組,就不能修改它的內(nèi)容。要創(chuàng)建一個元組,只需將逗號分隔的值放在括號中即可。以下是創(chuàng)建元組的幾種方法:
my_tuple = (1, 2, 3)
my_tuple = (1, 2, 3, 4, 5)
my_tuple = (1, "two", 3.0)
my_tuple = (1 + 2, "two", 3 * 3)
tuple()
函數(shù)將其他可迭代對象(如列表、集合或字符串)轉(zhuǎn)換為元組:my_list = [1, 2, 3]
my_tuple = tuple(my_list)
tuple()
函數(shù)將多個值作為參數(shù)傳遞并創(chuàng)建一個元組:my_tuple = tuple(1, 2, 3, 4, 5)