cs61a lecture17 iterations

1.Iterators

a container can procide an iteartor that provides acceess to its elements in some order.

iter(iterable)

next(iterator)

>>>s = [[1, 2], 3, 4, 5]
>>>next(s)
Error
>>>t = iter(s)
>>>next(t)
[1, 2]
>>>next(t)
3
>>list(t)
[4, 5]

2.View of a dictionary

an iterable value is ant value that can be passed to iter to produce an iterator

an iterator is returned from iter and can be passed to next;all iterators are mutable

a dictionary, its keys, its values and its items are all iterable values

    the order of items in a dictionary is the order in which they were added

    historically items apppeared in an arbitrary order(python 3.5 and earlier)

3.for statement

4.buit-in iterator functions

many built-in python sequence operation return iterators that compute results lazily(not immediately, only when you call the value)

>>>bcd ['b'. 'c'. 'd']
>>>map(lambda x: x.upper(), bcd)
>>>m = map(lambda x: x.upper(), bcd)
>>>next(m)
'B'
>>>t = [1, 2, 3, 2, 1]
>>>reversed(t)
<list_reverseiterator object at 0x101b7ad30>
>>>reversed(t) == t
False
>>>list(reversed(t))
[1, 2, 3, 2, 1]
>>>list(reversed(t)) == t
True
"""because reversed(t) is a iterator but not a list"""

5.generators and generator functions

a generator function is a function that yields vaaluse instead of returning them

a normal function returns once;a generator fnction can tield mutiple times

a generator is an iterator create automatically by calling a generator function

when agenerator gunction is called, it returns a generator thay iterates over its yields

6.generators can yield from iterators

a yield from tatement yields all values from an iterator or iterable

when meet yield value pause and return 

when next calling, continue from the pause place

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值