Slicing

1
2
3
4
5
L[:10:2] 
# [0, 2, 4, 6, 8]
L[::5] # 所有数,每5个取一个
# [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
L[:] # copy L

Iterating

1
2
for x, y in [(1, 1), (2, 4), (3, 9)]:
print(x, y)

List Comprehension

A list comprehension allows you to easily create a list based on some processing or selection criteria.

1
2
3
4
5
myList = [x * x for x in range(1, 11) if x % 2 != 0]
[ch.upper() for ch in 'comprehension' if ch not in 'aeiou'] combinations = [m + n for m in 'ABC' for n in 'XYZ']
# ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']

Generator

Referennce: https://www.liaoxuefeng.com/wiki/1016959663602400/1017318207388128

Create a generator:

1
2
3
4
5
6
7
8
9
10
L = [x * x for x in range(10)]
L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
g = (x * x for x in range(10))
g
<generator object <genexpr> at 0x1022ef630>
next(g)
0
>>> for n in g:
print(n)

Create a generator for fibbonacci:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def (k): # print first k fibbonacci number
n, a, b = 0, 0, 1
while n < k:
print(b)
a, b = b, a + b
n = n + 1
return 'done' def (max):
n, a, b = 0, 0, 1
while n < max:
yield b # Change print to yield, and fib would be a generator
a, b = b, a + b
n = n + 1
return 'done' >>> f = fib(6)
>>> f
<generator object fib at 0x104feaaa0>

generator和函数的执行流程不一样。函数是顺序执行,遇到return 大专栏  [Python] Advanced features语句或者最后一行函数语句就返回。而变成generator的函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def odd():
print('step 1')
yield 1
print('step 2')
yield(3)
print('step 3')
yield(5) >>> o = odd()
>>> next(o)
step 1
1
>>> next(o)
step 2
3
>>> next(o)
step 3
5
>>> next(o)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration

118. Pascal’s Triangle

Leetcode: https://leetcode.com/problems/pascals-triangle/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
def row(num):
n, prev, cur = 1, [1], [1, 1]
while n <= num:
yield prev
prev = cur
temp = [0] + prev + [0]
cur = [temp[i] + temp[i - 1] for i in range(1, len(temp))]
n += 1
return [r for r in row(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
2
3
4
>>> isinstance(iter([]), Iterator)
True
>>> isinstance(iter('abc'), Iterator)
True

Python的Iterator对象表示的是一个数据流,Iterator对象可以被next()函数调用并不断返回下一个数据,直到没有数据时抛出StopIteration错误。可以把这个数据流看做是一个有序序列,但我们却不能提前知道序列的长度,只能不断通过next()函数实现按需计算下一个数据,所以Iterator的计算是惰性的,只有在需要返回下一个数据时它才会计算。

Iterator甚至可以表示一个无限大的数据流,例如全体自然数。而使用list是永远不可能存储全体自然数的。

最新文章

  1. 设计模式——抽象工厂(Abstract Factory)
  2. 深入理解js——自由变量和作用域链
  3. spring-从普通java类取得注入spring Ioc容器的对象的方案
  4. PetaPoco模糊查询
  5. 面向切面编程AOP:基于注解的配置
  6. 怎样学法学?——民法学泰斗王利明教授的演讲 z
  7. 网页icon和文本对齐神技 2016.03.23
  8. configure HDFS(hadoop 分布式文件系统) high available
  9. [LeetCode] Redundant Connection II 冗余的连接之二
  10. [powershell] 批量重命名,修改文件名中的部分字符串
  11. SQL Server 中BIT类型字段增删查改那点事
  12. UVa 10970 大块巧克力
  13. hive多表联合查询(GroupLens-&gt;Users,Movies,Ratings表)
  14. thinkphp报错Call to undefined method app\index\controller\Index::fetch()
  15. 说说FATFS文件系统(转)
  16. indexes和indices的区别
  17. html5电池状态相关API
  18. c++基类指针指向继承类调用继承类函数
  19. Implementing DDD Reading - Strategic Design
  20. TestList汇总

热门文章

  1. Vue 源码学习(1)
  2. cmd执行jmeter命令生成报告的问题。
  3. 虚拟机virtualBox
  4. 我是如何从Java转型为Go区块链工程师
  5. 优秀的github java项目
  6. iOS 直接使用16进制颜色
  7. 吴裕雄--天生自然 JAVA开发学习:封装
  8. StatusBar时间状态栏
  9. 可用的 .net core 支持 RSA 私钥加密工具类
  10. 如何用java实现图片与base64转换