(for 廻圈) for 應用

摘要:(for 廻圈) for 應用


'''
當你使用 [] 包圍住 for 包含式(comprehension) 時,會建立 list 實例,如果使用 {} 的話,可以建立 set 實例,重複的元素會自動去除。
'''
lts = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print [ele for lt in lts for ele in lt] #[1,2,3,4,5,6,7,8,9]

sset={name for name in ['caterpillar', 'Justin', 'caterpillar', 'openhome']} #set 型態是無序群集,管理的元素不會重複
print sset #set(['caterpillar', 'Justin', 'openhome'])

names=['Tom',"Marry"]
passwds=[14848,151512]
ddict= {name : passwd for name, passwd in zip(names, passwds)} #dict 
print ddict  #{'Tom': 14848, 'Marry': 151512}

'''
zip 函式,就如名稱意義,會將兩個 list 像拉鏈一樣,兩兩相扣在一起為 tuple,這些 tuple 元素組成一個新的 list,
對於 tuple 元素組成的這個 list,每個 tuple 中的一對元素再指定給 name 與 passwd,最後這對 name 與 passwd 組成 dict 的一對鍵值。
'''