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 |
and execution flow generator function is not the same. Function execution order is encountered statement or statement returns the last line of the function. Becomes a function generator, each call time of execution, encounters statement returns, execution again returned from the last statement continues execution.return 大专栏 [Python] Advanced features
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's Iterator
object represents a data stream, Iterator
the object can be next()
invoked function and continue to return next data until the absence of data thrown StopIteration
error. This data stream can be seen as an ordered sequence, but we can not know in advance the length of the sequence, can only continue through the next()
realization of next-demand computing a data function, so the Iterator
calculations are inert, only need to return the next data it will be calculated.
Iterator
Even represent an infinite stream of data, such as all natural numbers. The use list
is never stored all natural numbers.