1. 程式人生 > 其它 >Python資料型別-Tuple(元組)

Python資料型別-Tuple(元組)

技術標籤:python3.0資料結構python

  1. Tuple(元組)
  2. Tuple(元組)與列表相似,不同之處在於元組的元素不能修改
  3. Tuple(元組)中的元素用小括號括起來,並用逗號隔開
  4. Tuple(元組)中的元素型別也可以不同
  5. 同樣支援切片操作
  6. 索引值從0開始,以-1結束
  7. 如果Tuple(元素)只有一個,寫成(1,)

具體的程式碼執行過程:

# 元組
t=('a','b','c')
t[1]=1  # 元組中的元素不能被修改
TypeError                                 Traceback (most recent call last)
<ipython-
input-42-5f612c647d12> in <module> 1 # 元組 2 t=('a','b','c') ----> 3 t[1]=1 TypeError: 'tuple' object does not support item assignment t=(1) type(t) int t=(t,) type(t) tuple # 經典的面試題 l=['A','B'] t=('a','b',l) t[2][0]='C' 元組不能改變是指元素指向不變,如果一個元素指向一個列表,指向不變,但所指向列表中的元素可改變 ('a', 'b'
, ['C', 'B']) l1=['A','B'] t[2]=l1 # 元組員素本身不能被改變,如下錯誤提示 TypeError Traceback (most recent call last) <ipython-input-54-da6e52aa1129> in <module> ----> 1 t[2]=l1 TypeError: 'tuple' object does not support item assignment