04元組、序列解包及生成器推導式

tuple元組(戴上枷鎖的列表)
  1 元組的創建 tuple = (2,4,1,54,0)   重點在於逗號
  2 元組的訪問 tuple1[0]  訪問tuple1的第一個元素
  3 元組的分片 slice   tuple1[start:stop]
元組不可修改
標誌爲 ,    
tuple2 = 5,
tuple3 = ()   爲空元組

對元組的操作
  利用切片slice間接對元組進行添加、刪減
>>> temp = (1,2,4,5,6)
>>> temp = temp[:2] + (3,) + temp[2:]
>>> temp
(1, 2, 3, 4, 5, 6)
1.序列解包
The statement t = 12345, 54321, 'hello!' is an example of tuple packing: the values 12345, 54321 and 'hello!' are packed together in a tuple. The reverse operation is also possible:
x,y,z = t
This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.
這被稱爲適當的序列解包,並適用於右側的任何序列。序列解包要求等號的左邊有多個變量,因爲序列中有元素。請注意,多重賦值實際上是元組打包和序列解包的組合。

可以使用序列解包功能對多個變量同時進行賦值:
>>> x,y,z = 1,2,3
>>> x
1
>>> y
2
>>> z
3
>>> 

>>> v_tuple=(False,2.5,'exp')
>>> x,y,z=v_tuple
>>> x
False
>>> y
2.5
>>> z
'exp'
>>> 
#序列解包也可以應用於字典和列表,但是對字典使用時,默認對‘鍵’進行操作。可以使用.values() .items()  
>>> a = [1,2,3]
>>> b,c,d = a
>>> c
2
>>> 

>>> s={'a':50,'b':'cdsad','k':'$$'}
>>> b,c,d=s.values()
>>> c
'cdsad'
>>> 

>>> s={'a':50,'b':'cdsad','k':'$$'}
>>> b,c,d=s.items()
>>> d
('k', '$$')
>>> 

>>> keys = ['adc','uzi','pdd','faker']
>>> values = [6,7,3,7]
>>> for i,j in zip(keys,values):
 print (i,j) 
adc 6
uzi 7
pdd 3
faker 7
>>> 


2.生成器推導式
類似於列表推導式,但與之不同的是,生成器推導式的結果是一個生成器對象,而不是列表,也不是元組。使用生成器對象的元素時,可以根據需要將其轉化爲列表或元組,也可以使用生成器對象的__next__()方法進行遍歷,或者直接將其作爲迭代器對象來使用。但不管用哪種方法訪問其元素,當所有元素訪問結束以後,如果需要重新訪問其中的元素,必須重新創建該生成器對象。
>>> g = ((i+2)**2 for i in range(10))
>>> g
<generator object <genexpr> at 0x000001EA21A89990>
>>> tuple(g) #轉化爲元組
(4, 9, 16, 25, 36, 49, 64, 81, 100, 121)
>>> tuple(g)
()  #元素已經遍歷結束
>>> 

>>> g = ((i+2)**2 for i in range(10))
>>> g.__next__()    #單步迭代
4
>>> g.__next__()
9
>>> g.__next__()
16
>>> 


發佈了41 篇原創文章 · 獲贊 1 · 訪問量 3373
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章