1. 程式人生 > 其它 >python基礎知識——內建資料結構(元組)

python基礎知識——內建資料結構(元組)

python中的內建資料結構主要有元組、列表和字典。本篇主要介紹元組。

元組由不同的元素組成,每個元素可以儲存不同型別的資料,如字串、數字甚至是元組。

1、元組的建立

格式

tuple_name = (元素1, 元素2, ...)

例如

tuple_1 = ('beijing', 'shanghai', 'wuhan')

注意點:

  1. 空元組的建立:tuple_2 = ()
  2. 只含一個元素的元組的建立:tuple_3 = ("beijing",) 若沒有“,”,則是建立的是字串“beijing”。

2、元組的訪問

和矩陣的訪問一致,通過索引訪問其中的元素。

格式

tuple_name [n]

如上述的tuple_1

tuple_1 = ('beijing', 'shanghai', 'wuhan')

print tuple_1 [0]#beijing

print tuple_1 [1]#shanghai

print tuple_1 [2]#wuhan

注意點:

元組支援負數索引,即從末尾開始是-1。

tuple_1 = ('beijing', 'shanghai', 'wuhan')

print tuple_1 [-3]#beijing

print tuple_1 [-2]#shanghai

print tuple_1 [-1]#wuhan

3、元組的分片

分片的含義是一個子集,定義兩個索引,分片是從第一個索引到第二個索引,不包括第二個索引之間的元素組成的元組。

格式

tuple_name [m:n]

例如

tuple_4 = ('beijing', 'shanghai', 'nanjing', 'wuhan', 'chongqing')

print len(tuple_4)

tuple_slice = tuple_4 [1:3]#('shanghai', 'nanjing')

print tuple_slice

4、二元元組

與二維陣列類似,即元組裡的元素是元組。

格式

tuple_name = (tuple_1, tuple_2, ...)

例如

#coding:UTF-8
tuple_1 = ('shanghai', 'beijing')#建立tuple_1

tuple_2 = ('nanjing', 'wuhan')#建立tuple_2

tuple_3 = (tuple_1, tuple_2)

#tuple_3的訪問
print tuple_3 [0] #訪問的是tuple_1
print tuple_3 [1] #訪問的是tuple_2

print tuple_3 [0][0] #訪問的是tuple_1中的shanghai

5、元組的“打包”和“解包”

在python中,將建立元組的過程稱為“打包”。

“解包”即是將元組中的各個元素分別賦值給多個變數。

例如

#coding:UTF-8

# 打包
tuple_1 = ('beijing', 'shanghai', 'wuhan', 'nanjing')

#解包
a, b, c, d = tuple_1
print a, b, c, d

6、元組的遍歷

使用到兩個函式len()和range()函式。

#coding:UTF-8

tuple_1 = ('beijing', 'shanghai', 'wuhan', 'nanjing')

for x in range(len(tuple_1)):
      print tuple_1 [x]

元組的注意點:元組的元素一旦確定就不能再修改。

#coding:UTF-8

tuple_1 = ('beijing', 'shanghai', 'wuhan', 'nanjing')

tuple_1 [1] = 'guangzhou'

想要修改'shanghai'的值為'guangzhou',結果報錯

TypeError: 'tuple' object does not support item assignment