[Python] Advanced features
Slicing
1 |
L[:10:2] |
Iterating
1 |
for x, y in [(1, 1), (2, 4), (3, 9)]: |
List Comprehension
A list comprehension allows you to easily create a list based on some processing or selection criteria.
1 |
myList = [x * x for x in range(1, 11) if x % 2 != 0] |
Generator
Referennce: https://www.liaoxuefeng.com/wiki/1016959663602400/1017318207388128
Create a generator:
1 |
L = [x * x for x in range(10)] |
Create a generator for fibbonacci:
1 |
def (k): # print first k fibbonacci number |
generator和函数的执行流程不一样。函数是顺序执行,遇到return 大专栏 [Python] Advanced features
语句或者最后一行函数语句就返回。而变成generator的函数,在每次调用next()
的时候执行,遇到yield
语句返回,再次执行时从上次返回的yield
语句处继续执行。
1 |
def odd(): |
118. Pascal’s Triangle
Leetcode: https://leetcode.com/problems/pascals-triangle/
1 |
def generate(self, numRows): |
Iterator
可以直接作用于for
循环的对象统称为可迭代对象:Iterable
. list
, set
, dict
, str
, tuple
.
而生成器不但可以作用于for
循环,还可以被next()
函数不断调用并返回下一个值,直到最后抛出StopIteration
错误表示无法继续返回下一个值了。可以被next()
函数调用并不断返回下一个值的对象称为迭代器:Iterator
All generators
are Interator
, not all Iterable
are Iterator
.(list
, set
, dict
, str
, tuple
)
But we can use iter()
to transform iterables into interator.
1 |
>>> isinstance(iter([]), Iterator) |
Python的Iterator
对象表示的是一个数据流,Iterator
对象可以被next()
函数调用并不断返回下一个数据,直到没有数据时抛出StopIteration
错误。可以把这个数据流看做是一个有序序列,但我们却不能提前知道序列的长度,只能不断通过next()
函数实现按需计算下一个数据,所以Iterator
的计算是惰性的,只有在需要返回下一个数据时它才会计算。
Iterator
甚至可以表示一个无限大的数据流,例如全体自然数。而使用list
是永远不可能存储全体自然数的。
最新文章
- 设计模式——抽象工厂(Abstract Factory)
- 深入理解js——自由变量和作用域链
- spring-从普通java类取得注入spring Ioc容器的对象的方案
- PetaPoco模糊查询
- 面向切面编程AOP:基于注解的配置
- 怎样学法学?——民法学泰斗王利明教授的演讲 z
- 网页icon和文本对齐神技 2016.03.23
- configure HDFS(hadoop 分布式文件系统) high available
- [LeetCode] Redundant Connection II 冗余的连接之二
- [powershell] 批量重命名,修改文件名中的部分字符串
- SQL Server 中BIT类型字段增删查改那点事
- UVa 10970 大块巧克力
- hive多表联合查询(GroupLens->;Users,Movies,Ratings表)
- thinkphp报错Call to undefined method app\index\controller\Index::fetch()
- 说说FATFS文件系统(转)
- indexes和indices的区别
- html5电池状态相关API
- c++基类指针指向继承类调用继承类函数
- Implementing DDD Reading - Strategic Design
- TestList汇总