Views in Python3.1?

前端 未结 3 998
天命终不由人
天命终不由人 2021-02-18 17:50

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 differ

3条回答
  •  难免孤独
    2021-02-18 18:21

    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'}
    

提交回复
热议问题