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. 吴裕雄--天生自然 PHP开发学习:表单 - 验证邮件和URL

    $name = test_input($_POST["name"]); if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $ ...

  2. 第3章 ZooKeeper基本数据模型

    第3章 ZooKeeper基本数据模型 3-1 zk数据模型介绍 3-2 zk客户端连接关闭服务端,查看znode ./zkCli.sh Ctrl + C 退出 =================== ...

  3. 实体机安装Ubuntu系统

    今天windows突然蓝屏了,索性安装个 Ubuntu 吧,这次就总结一下实体机安装 Ubuntu 的具体步骤 note: 本人实体机为笔记本 型号为:小米pro U盘为金士顿:8G 安装系统:Ubu ...

  4. Matlab高级教程_第一篇:Matlab基础知识提炼_06

    第十一节:图形操作 第十二节:文件的IO操作个格式化输出

  5. split - 拆分文件

    拆分文件 # 每个文件的行数为1000行 split -l 1000 test.txt # 将test文件拆分,20M一个文件 split -b 20M test.txt test文件拆分,并且文件名 ...

  6. linux中 su 与 su - 的区别

    linux中 su 与 su - 的区别 su只是切换了用户身份,shell环境仍然是切换前用户的shell环境 su -是用户和shell环境一起切换成. 备注:1.切换了shell环境会相应的用户 ...

  7. 单调栈and单调队列(此文太多坑了,以后再填)

    单调栈 单调栈是一种特殊的栈,特殊之处在于栈内的元素都保持一个单调性,可能为单调递增,也可能为单调递减. 性质: 单调栈里的元素具有单调性 元素加入栈前,会在栈顶端把破坏栈单调性的元素都删除 使用单调 ...

  8. springboot FreeMarker template error

    注释掉<#list>xxx</#list> 现在运行就不报错了

  9. Nginx配置使用

    1.黑色标注的得自己写入到nginx.conf文件中 upstream serverlb { server 127.0.0.1:9999; server 127.0.0.1:8888; } serve ...

  10. [LC] 1048. Longest String Chain

    Given a list of words, each word consists of English lowercase letters. Let's say word1 is a predece ...