标签:exce print 循环 int ict iterator enum catch bre
# 切片(获取list / tuple / 字符串 中指定的元素)
l = list(range(10)) l[0:3] l[:3] # 0可以省略 l[:] # 全部 l[3:] # 最后的可以省略 l[-2:-1] # 负数下标,见python笔记2中介绍 l[-10:] # 取最后10个数 l[::2] # 所有数,每个两个取出
# 迭代
from collections import Iterable isinstance(‘abc‘, Iterable)
for i, value in enumerate([‘A‘,‘B‘,‘C‘]) : print(i, value)
for x,y in [(1,2), (3,4)] : print(x, y)
# 列表生成式(一句话生成需要的 list)
list(range(2,10))
[x*x for x in range(1,10)] [x*x for x in range(1,10) if x%2 == 0] [m+n for m in ‘ABCD‘ for n in ‘12345‘]
d = {‘x‘:‘A‘, ‘y‘:‘B‘} >>>[k+‘=‘+c for k,v in d.items()] [‘x=A‘, ‘y=B‘]
# 生成器(得到的是“函数”规则,而非结果)
g = (x*x for x in range(10)) >>>next(g) # 获得生成器的结果
# 函数 def dplist(l) : for sub in l : print(sub) return ‘done‘ # 生成器 def dplist(l) : for sub in l : yield(sub) return ‘done‘
添加了 yield 的地方更像是一个函数的运行断点,每次运行都是承接上次的运行结果。不会循环,到末了就会报终止错误,该错误可以catch
>>>def dplist() : for sub in range(10) : yield(sub) return ‘done‘ >>>g = dplist()
>>>while True: try: x=next(g) print(‘g = ‘, x) except StopIteration as e: print(‘Genearator return vaue : ‘, e.value) break
# 迭代器
可以用于for循环的:list、tuple、dict、set、str、生成器(generator)等
判断方法
from collections import Iterable >>>isinstance([], Iterable)
from collections import Iterator >>>isinstance([], Iterator)
生成器才是“迭代对象”,可以使用next
list、tuple、dict、set、str、生成器(generator)是“可迭代”对象,不能使用next
isinstance(iter([]), Iterator)
迭代器因为是一种规则,所以理论上可以表示所有的整数。但是诸如 list 就不可以。
标签:exce print 循环 int ict iterator enum catch bre
原文地址:http://www.cnblogs.com/alexYuin/p/7044453.html