-
Notifications
You must be signed in to change notification settings - Fork 0
/
iter.py
50 lines (40 loc) · 1.07 KB
/
iter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/usr/bin/env python3
# encoding: utf-8
# @author: hoojo
# @email: hoojo_@126.com
# @github: https://github.com/hooj0
# @create date: 2017-11-04 18:34:40
# @copyright by hoojo@2018
# @changelog Added python3 `data struct->iter` example
from symbol import except_clause
import sys
'''
迭代器
特点:
1、对任意集合进行迭代遍历
2、只能向前不能后退
example:
iter = iter({ 'name': 'jack', 'age': 22, 'brithday': (2010, 10, 22) })
使用iter()方法进行构造
API:
next() 下一个元素
'''
# iter 构造迭代器
it = iter({ 'name': 'jack', 'age': 22, 'brithday': (2010, 10, 22) })
# next下一个元素
print('next element:', next(it)) # next element: name
print('next element:', next(it)) # next element: age
list = [1, 3, 2, 5]
# 循环遍历
it = iter(list)
for el in it:
print('iter el:', el, end = ',\t') # iter el: 1, iter el: 3, iter el: 2, iter el: 5,
print()
# 循环遍历
it = iter(list)
while True:
try:
print(next(it))
except Exception:
print('exit')
sys.exit()