(强调:这是期末作业,不是Python教程)
随后的课程内容包括了一部分Python高级特性,包括迭代器、生成器、异常处理、面向对象编程、匿名函数等等。
首先,我们需要理解迭代的概念:所谓迭代,即用循环来遍历可迭代对象。判断对象是否可迭代:
from collections import Iterable
isinstance('123', Iterable) # True
isinstance(123, Iterable) # False
迭代的一般形式是for 变量 in 可迭代对象:
,例如:
d = {
'a': 97, 'b': 98, 'c': 99}
for key, val in d.items():
print(key + '=' + val)
# b = 98
# a = 97
# c = 99 (unordered)
# Or instead:
[key + '=' + val for key, val in d.items()]
# ['b=98', 'a=97', 'c=99']
上面的第二种方法用到了列