一入python深似海–Views in Python3.1

最后更新于:2022-04-02 00:35:25

在Python3中,Views(视图)的作用,类似于数据库中视图的一个作用,能够反映所对应对象的变化。就像数据库表变化后,视图查询的结果是变化后的值一样,python中通过Views查询的值也是这样的。 Python3中,dict.keys(),dict.items(),dict.values()返回的是Views,而不是list。可以通过list()函数将Views()转换为list。 下面是一个说明Views作用的例子: ~~~ >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500} >>> keys = dishes.keys() >>> values = dishes.values() >>> # 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'} ~~~
';