>>a = [ [1,2,3], [4,5,6], [7,8,9] ]
>>zip( *a ) # 等同於 zip( [1,2,3], [4,5,6], [7,8,9] )
>>[ (1,4,7), (2,5,8), (3,6,9) ] # 矩陣轉置
zip 會擷取每個迭代物件所對應的元素放入tuple中
第一個tuple 內含每個list的第一個元素,第二tuple 則是第二元素
以此類推。
>> s = 'abcdefghi'
>>zip( *[iter(s)]*3 )
>>[ ( 'a', 'b', 'c' ), ( 'd', 'e', 'f' ), ( 'g', 'h', 'i' ) ] # 字串切割成一塊塊
將字串切成同樣字元數的範例原理是因爲迭代器 iter
在每次呼叫時都會以 __next__ 取出一個元素
而在 [ iter(s) ] * 3 這步驟,並不是生成三個迭代字串s 的list
而是生成一個list, 裏面的三個元素的參照都指向同迭代器
>> [ iter(s) ]*3
>> [ <iterator object at 0xaddress>, <iterator object at 0xaddress>,
<iterator object at 0xaddress> ]
因此當zip 在生成第一個tuple時,在list元素一的iter 回傳字串的第一個字
而去list元素二時,由於仍是同一個迭代器,此時會回傳第二個字
以此類推。
感覺像是這樣:
tuple1 tuple2 tuple3
---------- ---------- -----------
abcdefghi abcdefghi abcdefghi
abcdefghi abcdefghi abcdefghi
abcdefghi abcdefghi abcdefghi
沒有留言:
張貼留言