1. 程式人生 > >(一)Python入門-3序列:10元組-元素訪問-計數方法-切片操作-成員資格判斷-zip()

(一)Python入門-3序列:10元組-元素訪問-計數方法-切片操作-成員資格判斷-zip()

mod trac peer 計數 assign item sig traceback span

一:元組的元素訪問和計數

  1. 元組的元素不能修改

 1 >>> a = (20,10,30,9,8)
 2       
 3 >>> a
 4       
 5 (20, 10, 30, 9, 8)
 6 >>> a[3]
 7       
 8 9
 9 >>> a[3] = 999
10       
11 Traceback (most recent call last):
12   File "<pyshell#297>", line 1, in <module>
13
a[3] = 999 14 TypeError: tuple object does not support item assignment

  2. 元組的元素訪問和列表一樣,只不過返回的仍然是元組對象。

 1 >>> a = (20,10,30,9,8)
 2       
 3 >>> a
 4       
 5 (20, 10, 30, 9, 8)
 6 >>> a[1]
 7       
 8 10
 9 >>> a[1:3]
10       
11 (10, 30)
12 >>> a[:4]
13 14 (20, 10, 30, 9)

  3. 列表關於排序的方法list.sorted()是修改原列表對象,元組沒有該方法。如果要對元組排 序,只能使用內置函數 sorted(tupleObj),並生成新的列表對象。

1 >>> a = (20,10,30,9,8)
2       
3 >>> a
4       
5 (20, 10, 30, 9, 8)
6 >>> sorted(a)
7       
8 [8, 9, 10, 20, 30]

二:zip()方法

  zip(列表 1,列表2,...)將多個列表對應位置的元素組合成為元組,並返回這個 zip對象。

 1 >>> a = [10,20,30]
 2       
 3 >>> b = [40,50,60]
 4       
 5 >>> c = [70,80,90]
 6       
 7 >>> d = zip(a,b,c)
 8       
 9 >>> d
10       
11 <zip object at 0x0000011864365548>
12 >>> list(d)
13       
14 [(10, 40, 70), (20, 50, 80), (30, 60, 90)]
15 >>> list(d)
16       
17 []

(一)Python入門-3序列:10元組-元素訪問-計數方法-切片操作-成員資格判斷-zip()