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. java网络考试系统的设计与实现 jsp 源码

    开发环境: Windows操作系统开发工具:MyEclipse/Eclipse + JDK+ Tomcat + MySQL 数据库 项目简介: 网络考试系统主要用于实现高校在线考试,基本功能包括:自动 ...

  2. 一个支持种子、磁力、迅雷下载和磁力搜索的APP源代码

    磁力搜索网站2020/01/12更新 https://www.cnblogs.com/cilisousuo/p/12099547.html 一个支持种子.磁力.迅雷下载和磁力搜索的APP源代码 Lic ...

  3. np.newaxis 为 numpy.ndarray(多维数组)增加一个轴

    >> type(np.newaxis) NoneType np.newaxis 在使用和功能上等价于 None,其实就是 None 的一个别名. 1. np.newaxis 的实用 > ...

  4. Java线程——线程之间的几点重要说明

    在Java中,可以通过配合调用Object对象的wait()方法和notify()方法或notifyAll()方法来实现线程间的通信.在线程中调用wait()方法,将阻塞等待其他线程的通知(其他线程调 ...

  5. 虚拟机virtualBox

    在笔记本了装了一个虚拟机, 并安装了Linux系统, 方便测试linux 命令. 考虑到不需要图形界面, 学习了用命令行操作虚拟机, 配置如下 linux 下安装openssh-server 虚拟机设 ...

  6. tomcat启动极慢在linux生产环境

    在window环境下不会出现启动极慢的问题.   Tomcat启动极慢在生产环境,跟Weblogic一样   此外由于Weblogic创建域的时候使用的JDK是自带的jrockit,所以要解决WebL ...

  7. MyBatis从入门到精通(第9章):Spring集成MyBatis(下)

    MyBatis从入门到精通(第9章):Spring集成MyBatis(下) springmvc执行流程原理 mybatis-spring  可以帮助我们将MyBatis代码无缝整合到Spring中.使 ...

  8. php中openssl_pkey_get_private()函数遇到false的问题 解决办法

    今天用openssl_pkey_get_private()函数遇到了一个大坑: 如果你的私钥文件(private_key.pem)是 -----BEGIN PRIVATE KEY-----字符串字符串 ...

  9. centos快速安装mysql

    1. wget http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm 2. rpm -ivh mysql-community-r ...

  10. centos7 安装gdb (调试nginx)

    首先卸载原有的gdb,sudo yum remove gdb 从gnu官网下载最新的gdb源文件,wget http://mirrors.ustc.edu.cn/gnu/gdb/gdb-7.9.1.t ...