|
序列拆分: for x,y in ((-3,4),(5,12),(28,-45)): print(math.hypot(x,y))命名的元組:collection.namedtuple("元組名","索引名1 索引名2 ...") Sale=colections.namedtuple("Sale","productid customerid date quantity price") sales=[] sales.append(Sale(432,921,"2008-09-14",3,7.99))sales.append(Sale(419,874,"2008-09-15",1,18.49)) print("{0:.2f}".format(sale.quantity*sale.price)) #使用索引名稱引用 namedtuple._asdict()返回鍵值對映射,用**將映射拆分轉(zhuǎn)換為str.format()方法的鍵-值參數(shù) “{quantity}{price}”.format(**sale._asdict()) 任意可以迭代的(列表、元組等)數(shù)據(jù)類型都可以使用序列拆分操作符進行拆分,即*。賦值操作符左邊的兩個或多個變量時,其中的一個使用*進行引導(dǎo),數(shù)據(jù)項將賦值給該變量,而所有剩下的數(shù)據(jù)項將賦值給帶*號的變量: first,*rest=[9,2,-4,8,7] #(9,[2,-4,8,7]) L=[2,3,4]product(*L) # 等價于product(2,3,4) 列表內(nèi)涵:[expression for item in iterable if condition] 固定集合只能用frozenset()數(shù)據(jù)類型函數(shù)進行創(chuàng)建,如果二元運算符應(yīng)用于集合和固定集合,那么產(chǎn)生結(jié)果的數(shù)據(jù)類型與左邊操作數(shù)的類型一致,如果f是固定集合,s是集合,f&s將產(chǎn)生固定集合,s&f產(chǎn)生一個集合。因為固定集合不可更改,所以可以作為子項包含進集合。 集合內(nèi)涵:{expression for item in iterable if condition} 字典創(chuàng)建方法: dict({"id":1948,"name":"washer","size":3}) dict(id=1948,name="washer",size=3) #使用關(guān)鍵字參數(shù)創(chuàng)建dict([("id",1948),("name":"washer"),("size":3)]) #從列表創(chuàng)建 字典內(nèi)涵:{keyexpression:valueexpression for key,value in iterable if condition} 默認字典:collections.defaultdict(int) #int為工廠函數(shù),創(chuàng)建默認值 words=collections.defaultdict(int) x=words["xyz"] #將調(diào)用int()將鍵"xyz"對應(yīng)的值初始化為0有序字典:collections.OrderedDict(('z',-4),('e',19),('k',7)) 改變值的時候順序不會改變。 |
|
|