python 笔记3--高级特性
2015-09-19 09:16
519 查看
切片
语法
L[l:r] 取L[l],L[l+1]…L[r-2],L[r-1]L[l:r:m] 取L[l],L[l+m],L[l+2*m],L[l+3*m]….(满足l+n*m<=r-1)
tips
字符串,tuple也可以切片迭代
dict
迭代key>>> for key in d: print(key)
迭代value
for value in d.values()
迭代key和value
for value,key in d.items(): print(value,key)
字符串
语法>>> for ch in 'ABC': ... print(ch)
判断是否属于迭代对象
>>> from collections import Iterable >>> isinstance('abc', Iterable) # str是否可迭代 True >>> isinstance([1,2,3], Iterable) # list是否可迭代 True >>> isinstance(123, Iterable) # 整数是否可迭代 False
调用索引-元素(enumerate)
>>> for i, value in enumerate(['A', 'B', 'C']): ... print(i, value) ... 0 A 1 B 2 C
引用两个变量
>>> for x, y in [(1, 1), (2, 4), (3, 9)]: ... print(x, y) ... 1 1 2 4 3 9
列表生成器
普通list
list(range(1, 11)) 或者循环型 [m for m in list(range(1,11))]
多重循环
>>> [m + n for m in 'ABC' for n in 'XYZ'] ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
带判断语句
[x * x for x in range(1, 11) if x % 2 == 0] [4, 16, 36, 64, 100] //isinstance 判断一个变量是否是某个类型 ['Hello', 'World', 18, 'Apple', None] [s.lower() if isinstance(s,str) else s for s in L] ['hello', 'world', 18, 'apple', None]
生成器
-普通的generator(x * x for x in range(10))
- 函数 generator
def fib(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n = n + 1 return 'done'
原理:
这里,最难理解的就是generator和函数的执行流程不一样。函数是顺序执行,遇到return语句或者最后一行函数语句就返回。而变成generator的函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。
捕获return
比较麻烦,暂时不理
小作业
杨辉三角的generator
def triangle(n): L=[1] while True: yield(L) L.append(0) L=[L[i]+L[i-1] for i in range(len(L))] if len(L)>n: return "done" g=triangle(100) for i in g: print(i)
这一句比较奇异,L全部计算完后才赋值给原来的L。
L=[L[i]+L[i-1] for i in range(len(L))]
迭代器
小结
凡是可作用于for循环的对象都是Iterable类型;
是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计的序列;
集合数据类型如list、dict、str等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象。
相关文章推荐
- python 笔记3--高级特性
- 文章推荐集合页推荐学习Python Django 开发机开发人参考
- Python的输入和raw_input()内建函数等以及相关运算符
- Windows Sublime Text3配置Python
- python 用request模块发送cookie,发送多文件。django后台做转发。代码
- 零基础学python-18.4 函数对象:间接调用函数
- 零基础学python-18.4 函数对象:间接调用函数
- python 什么叫迭代
- Ubuntu安装Python的包管理工具Pip
- xjtu_001:寻找完全数,并对完全数分类
- python语言简单了解
- Python C :ctypes库
- [LeetCode]题解(python):015-3Sum
- python 3.3.2报错:No module named 'urllib2'
- python 3.3.2报错:No module named 'urllib2'
- python下libsvm的使用
- 送给半路出家的Pythoner
- Sublime Text 3 打造舒服的工具(直接运行python)
- Windows下如何构建和发布Python模块
- Python网页爬虫学习