Python3.1 中的视图? [英] Views in Python3.1?

查看:25
本文介绍了Python3.1 中的视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python3.1 中的视图到底是什么?它们的行为方式似乎与迭代器类似,并且它们也可以具体化为列表.迭代器和视图有何不同?

解决方案

据我所知,视图仍然附加到创建它的对象上.对原始对象的修改会影响视图.

来自文档(用于字典视图):

<预><代码>>>>菜肴 = {'鸡蛋':2,'香肠':1,'培根':1,'垃圾邮件':500}>>>钥匙 = 菜肴.钥匙()>>>值 = 菜肴.值()>>># 迭代>>>n = 0>>>对于 val 值:... n += val>>>打印(n)504>>># 键和值以相同的顺序迭代>>>列表(键)['鸡蛋'、'培根'、'香肠'、'垃圾邮件']>>>列表(值)[2, 1, 1, 500]>>># 视图对象是动态的并反映字典的变化>>>德尔菜肴['鸡蛋']>>>del 菜肴['香肠']>>>列表(键)['垃圾邮件','培根']>>># 设置操作>>>钥匙&{'鸡蛋'、'培根'、'沙拉'}{'熏肉'}

What exactly are views in Python3.1? They seem to behave in a similar manner as that of iterators and they can be materialized into lists too. How are iterators and views different?

解决方案

From what I can tell, a view is still attached to the object it was created from. Modifications to the original object affect the view.

from the docs (for dictionary 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'}

这篇关于Python3.1 中的视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆