标签:
通过dict.viewkkeys(),dict.viewvalues()以及dict.viewitems()的对象称之为视图对象。它们提供了字典对象的一个动态视图,也就是说当字典中内容改变的时候,视图也跟着改变。
>>> dishes ={‘eggs‘:2,‘sausage‘:1,‘bacon‘:1,‘spam‘:500} >>> keys = dishes.viewkeys() >>> values = dishes.viewvalues() >>># iteration >>> n =0 >>>for val in values: ... n += val >>>print(n) 504 >>># keys and values are iterated over in the same order >>> list(keys) [‘eggs‘,‘bacon‘,‘sausage‘,‘spam‘] >>> list(values) [2,1,1,500] >>># view objects are dynamic and reflect dict changes >>>del dishes[‘eggs‘] >>>del dishes[‘sausage‘] >>> list(keys) [‘spam‘,‘bacon‘] >>># set operations >>> keys &{‘eggs‘,‘bacon‘,‘salad‘} {‘bacon‘}
标签:
原文地址:http://www.cnblogs.com/fireflow/p/4868859.html