[Python] Advanced features

Slicing

12345
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

12
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.

12345
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:

12345678910
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:

12345678910111213141516171819
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语句处继续执行。

12345678910111213141516171819202122
def odd():    print('step 1')    yield 1    print('step 2')    yield(3)    print('step 3')    yield(5)

>>> o = odd()>>> next(o)step 11>>> next(o)step 23>>> next(o)step 35>>> 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/

1234567891011121314
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.

1234
>>> isinstance(iter([]), Iterator)True>>> isinstance(iter('abc'), Iterator)True

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

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

原文地址:https://www.cnblogs.com/lijianming180/p/12366611.html

时间: 2024-10-10 11:06:42

[Python] Advanced features的相关文章

Open vSwitch Advanced Features Tutorial

Open vSwitch Advanced Features Tutorial ======================================= Many tutorials cover the basics of OpenFlow. This is not such a tutorial. Rather, a knowledge of the basics of OpenFlow is a prerequisite. If you do not already understan

Advanced Features of Delphi DLLs

http://www.delphisources.ru/pages/faq/master-delphi-7/content/LiB0104.html Beside this introductory example, you can do a few extra things with dynamic libraries in Delphi. You can use some new compiler directives to affect the name of the library, y

十七、Python SQLAlchemy

SQLAlchemy tutorial 关于这个教程 This tutorial is for SQLAlchemy version 0.2. You may notice that some sections are marked "New in 0.2". If this is the first time you're reading this tutorial, you can safely skip those sections. On the other hand, if

python小技巧(转)

http://blog.jobbole.com/63320/ 30 Python Language Features and Tricks You May Not Know About Posted on Mar 05, 2014 , last modified on May 19, 2014 - Permanent link 1   Introduction Since I started learning Python, I decided to maintain an often visi

python补充最常见的内置函数

最常见的内置函数是: print("Hello World!") 数学运算 abs(-5)                         # 取绝对值,也就是5 round(2.6)                       # 四舍五入取整,也就是3.0 pow(2, 3)                        # 相当于2**3,如果是pow(2, 3, 5),相当于2**3 % 5 cmp(2.3, 3.2)                   # 比较两个数的大小

python函数: 内置函数

forthttp://blog.csdn.net/pipisorry/article/details/44755423 Python内置函数 Python内置(built-in)函数随着python解释器的运行而创建.在Python的程序中,你可以随时调用这些函数,不需要定义. Built-in Functions     abs() dict() help() min() setattr() all() dir() hex() next() slice() any() divmod() id(

The Most Advanced VVDI 2.8.0 VAG Vehicle Diagnostic Interface

Almost a month, a new version for VVDI VAG vehicle diagnostic tool will be launched, which means that VVDI has constantly been improved so as to meet the demand of comprehensive users. And now VVDI has been updated to the newest V2.8.0, here let’s co

PEP 443 单分派泛型函数 -- Python官方文档译文 [原创]

PEP 443 -- 单分派泛型函数(Single-dispatch generic functions) 英文原文:https://www.python.org/dev/peps/pep-0443 采集日期:2020-03-17 PEP: 443 Title: Single-dispatch generic functions Author: ?ukasz Langa [email protected] Discussions-To: Python-Dev [email protected]

深入浅出JMS(二)--ActiveMQ简单介绍以及安装

现实的企业中,对于消息通信的应用一直都非常的火热,而且在J2EE的企业应用中扮演着特殊的角色,所以对于它研究是非常有必要的. 上篇博文深入浅出JMS(一)–JMS基本概念,我们介绍了消息通信的规范JMS,我们这篇博文介绍一款开源的JMS具体实现--ActiveMQ.ActiveMQ是一个易于使用的消息中间件. 消息中间件 我们简单的介绍一下消息中间件,对它有一个基本认识就好,消息中间件(MOM:Message Orient middleware). 消息中间件有很多的用途和优点: 1. 将数据从