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是永远不可能存储全体自然数的。

[Python] Advanced features的更多相关文章

  1. [Angular] Angular Advanced Features - ng-template , ng-container, ngTemplateOutlet

    Previously we have tab-panel template defined like this: <ul class="tab-panel-buttons" ...

  2. Python 高级网络操作 - Python Advanced Network Operations

    Python 高级网络操作 - Python Advanced Network Operations Half Open Socket, 一个单向的 socket 被称为 half open sock ...

  3. python advanced programming (Ⅲ)

    IO编程 IO在计算机中指Input/Output.由于程序和运行时数据是在内存中驻留,由CPU来执行,涉及到数据交换的地方,通常是磁盘.网络等,就需要IO接口. IO编程中,Stream(流)是一个 ...

  4. python advanced programming ( II )

    面向对象编程 简称OOP,是一种程序设计思想.OOP把对象作为程序的基本单元,一个对象包含了数据和操作数据的函数.数据封装.继承和多态是面向对象的三大特点. 在Python中,所有数据类型都可以视为对 ...

  5. python advanced programming ( I )

    函数式编程 函数是Python内建支持的一种封装,通过把大段代码拆成函数,通过一层一层的函数调用,就可以把复杂任务分解成简单的任务,这种分解可以称之为面向过程的程序设计.函数就是面向过程的程序设计的基 ...

  6. Advanced Features of Delphi DLLs

    http://www.delphisources.ru/pages/faq/master-delphi-7/content/LiB0104.html Beside this introductory ...

  7. [转]Advanced Oracle SQL Developer Features

    本文转自:http://www.oracle.com/technetwork/cn/server-storage/linux/sqldev-adv-otn-092384.html Advanced O ...

  8. python工程设置工具(pipenv)

    原始安装 pip工具 --- 包安装工具, 可以从Python包索引hub上安装,也可以使用自定义的hub. 命令: pip install xxx 缺点: 1.命令方式, 一次只能安装一个包, 对于 ...

  9. Create Advanced Web Applications With Object-Oriented Techniques

    Create Advanced Web Applications With Object-Oriented Techniques Ray Djajadinata Recently I intervie ...

随机推荐

  1. cmd执行jmeter命令生成报告的问题。

    现有几个jmeter脚本,准备以命令行的方式执行jmeter脚本,并生成报告. 一.使用python语言处理 1.目录结构 2.说明 jmx目录下是jmeter脚本 result目录下是生成的报告及文 ...

  2. 熟练使用WebApi开发

    在建立WebApi框架的时候,要想自己的业务需求是什么.例如PC端(前端),APP端都要使用的同一接口,就得考虑Webapi来提供接口支持了.最近公司刚好让我整合一下公司的接口项目(有WebServi ...

  3. 半监督的GAN算法

    ImprovedGAN $ Loss = Loss_{supervised}   + \lambda * Loss_{unsupervised} $ 第二项形式与原始的GAN模型类似. 参考: Imp ...

  4. 吴裕雄--天生自然MySQL学习笔记:MySQL 管理

    启动及关闭 MySQL 服务器 Windows 系统下 在 Windows 系统下,打开命令窗口(cmd),进入 MySQL 安装目录的 bin 目录. 启动: cd c:/mysql/bin mys ...

  5. 01 语言基础+高级:1-8 File类与IO流_day08【 File类、递归】

    day08[File类.递归] 主要内容 File类 递归 教学目标 能够说出File对象的创建方式 能够说出File类获取名称的方法名称 能够说出File类获取绝对路径的方法名称 能够说出File类 ...

  6. LUA函数闭包

    词法定界:当一个函数内嵌套另一个函数的时候,内函数可以访问外部函数的局部变量,这种特征叫做词法定界 table.sort(names,functin (n1,n2) return grades[n1] ...

  7. [CTSC2008]祭祀(二分图匹配)

    没有SPJ时显然是不需要输出方案的.不需要输出方案很好做,先把边扩展(因为会往下流),然后求最大独立集,最大独立集=n-最小点覆盖,因为其是最大独立集的补集.如何求最小点覆盖呢?毕竟我写过最大权闭合子 ...

  8. 编译Python文件

    编译Python文件 一.编译Python文件 为了提高加载模块的速度,强调强调强调:提高的是加载速度而绝非运行速度.python解释器会在__pycache__目录中下缓存每个模块编译后的版本,格式 ...

  9. python 拆解包

    Python 拆解包 转自:https://www.jianshu.com/p/22c538a58bcc python中的解包可以这样理解:一个list是一个整体,想把list中每个元素当成一个个个体 ...

  10. ZJNU 1129 - The sum problem——中级

    枚举区间可能的长度len,将m减去1~len构成的序列和后如果结果是len的倍数,则可以构成答案区间. /* Written By. StelaYuri */ #include<stdio.h& ...