在 Python 中,元組是不可變的數(shù)據(jù)類型,因此不能直接修改或添加元組的元素。但可以通過以下方法間接實(shí)現(xiàn)添加數(shù)據(jù)到元組的目的:
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
new_tuple = tuple1 + tuple2
print(new_tuple) # 輸出:(1, 2, 3, 4, 5, 6)
tuple1 = (1, 2, 3)
list1 = [4, 5, 6]
new_tuple = tuple1 + tuple(list1)
print(new_tuple) # 輸出:(1, 2, 3, 4, 5, 6)
這些方法都是創(chuàng)建一個(gè)新的元組,并將原有的元組和要添加的數(shù)據(jù)連接起來,而不直接修改原有的元組。