Python高级特性之:List Comprehensions、Generator、Dictionary and set ...
Python高级特性之:List Comprehensions、Generator、Dictionary and set comprehension(su013171165)
我们在需要循环处理数据的时候,往往都会用range(n)这个方法生成list但是如果需要生成奇数list或者其他list怎么办呢?这就是我今天要讲的List Comprehensions。
一、List Comprehensions(列表解析/列表生成器)方法一:循环l.append()>>> L = []>>> for i in range(10): if i % 2 == 1: L.append(i) >>> L[1, 3, 5, 7, 9]需要注意的是:xrange()消耗的内存小,只做迭代处理的话,推荐一律用xrange()。
help()原文:Like range(), but instead of returning a list, returns an object that generates the numbers in the range on demand. For looping, this is slightly faster than range() and more memory efficient.
方法二:range用法【2014.06.01补充:生成奇偶数其实可以用range,但是本文讲的是list comprehensions。
>>> range(0, 10,2)[0, 2, 4, 6, 8]
】
方法三:使用List ComprehensionsList Comprehensions语法:[expr for iter_var in iterable] 或 [expr for iter_var in iterable if cond_expr]
L = [expr for iter_var in iterable]:for iter_var in iterable的作用是依次取 iterable赋值给iter_var,而expr for iter_var in iterable的作用就是依次取值给iter_var,expr做运算后,继续循环,expr运算得到的值赋给变量L
>>> L = [i % 2 == 1 for i in range(10)]>>> L[False, True, False, True, False, True, False, True, False, True]>>> L = [i + 1 for i in range(5)]>>> L[1, 2, 3, 4, 5]>>>
请注意上面两个表达式的不同结果。
L = [expr for iter_var in iterable if cond_expr]:加了判断条件if cond_expr,也就是满足了判断条件才按expr运算iter_var。
>>> L = (i for i in range(10) if i % 2 ==1)>>> L<generator object <genexpr> at 0x02950F80>>>> for i in L: print i 13579需要注意的是:第二种方法返回的不是一个list是一个generator(生成器)对象!为什么呢,我们用的是()而不是[],是不是有人写错了?
>>> L = [i for i in range(10) if i % 2 ==1]>>> L[1, 3, 5, 7, 9]>>> 下面会讲生成器。
注:还有很多其他用法,有需求,就有使用的空间,简单写两个。
1、多层循环
>>> L = [a * b for a in range(1, 10) for b in range(1, 10)]>>> L[1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 4, 6, 8, 10, 12, 14, 16, 18, 3, 6, 9, 12, 15, 18, 21, 24, 27, 4, 8, 12, 16, 20, 24, 28, 32, 36, 5, 10, 15, 20, 25, 30, 35, 40, 45, 6, 12, 18, 24, 30, 36, 42, 48, 54, 7, 14, 21, 28, 35, 42, 49, 56, 63, 8, 16, 24, 32, 40, 48, 56, 64, 72, 9, 18, 27, 36, 45, 54, 63, 72, 81]2、用等连接字典的键值:key=value
>>> d = {1: 'A', 2: 'B', 3: 'C' }>>> [str(k) + '=' + v for k, v in d.iteritems()]['1=A', '2=B', '3=C']>>> 二、Generator(生成器)官方demo:https://wiki.python.org/moin/Generators 建议迭代的时候能用generator就用!
为什么我推荐生成器呢。因为list大的时候很占内存,会受到内存限制;如果我们需要用的元素少,岂不是浪费得很?
generator的机制为:一边循环,一边计算!
generator的创建方法:1、把List Comprehensions中的[]换为(),上面有例子,不在贴出代码。有些是不能用List Comprehensions写出来的,例如斐波那契数列用,怎么办呢? 百度百科:斐波拉契数列 维基百科:菲波拉契数列
斐波那契数列,又称黄金分割数列,指的是这样一个数列:0、1、1、2、3、5、8、13、21、……在数学上,斐波纳契数列以如下被以递归的方法定义:F0=0,F1=1,Fn=F(n-1)+F(n-2)(n>=2,n∈N*)。
这个就需要用函数了!但是普通函数不能生成generator,需要用到yield关键字。
2、yield关键字首先不得不说下generator值的取法:用for循环;用next()方法。
>>> L = (i for i in range(10) if i % 2 != 1)>>> L<generator object <genexpr> at 0x029518A0>>>> for i in L: print i 02468>>> for i in L: print i >>>有没有疑问呢?再看next()方法是什么样的。
>>> L = (i for i in range(10) if i % 2 != 1)>>> L.next()0>>> L.next()2>>> L.next()4>>> L.next()6>>> L.next()8>>> L.next()Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> L.next()StopIteration>>> for i in L: print i >>> 我们发现了什么?L的值被取过一遍后再也取不出来了!next()会报错,for 循环取不出来任何值。
原因是:它并不把所有的值放在内存中,它是实时地生成数据,所以只可以取值一次!
其他的迭代器方法,如下图:
Help on generator object:
<genexpr> = class generator(object)
| Methods defined here:
| close(...)
| close() -> raise GeneratorExit inside generator.
| # 抛出generator内部的GeneratorExit异常,达到停止generator的目的
>>> L = (i for i in range(10) if i % 2 != 1)>>> L.next()0>>> L.close()>>> L.next()Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> L.next()StopIteration>>> | next(...)
| x.next() -> the next value, or raise StopIteration
| # 取下一个值,所有都取过则抛出异常StopIteration
| send(...)
| send(arg) -> send 'arg' into generator,
| return next yielded value or raise StopIteration.
| # 传递参数进入generator,返回下一个yielded的值直到抛出StopIteration异常。
| throw(...)
| throw(typ[,val[,tb]]) -> raise exception in generator,
| return next yielded value or raise StopIteration.
| # 未知用法,暂未涉及
| ----------------------------------------------------------------------
下面用斐波那契数列学习generator:
>>> def fbnq(max): # 生成max个元素的斐波那契数列 L = [] a, b, n = 0, 1, 0 while n < max: L.append(b) a, b = b , a + b n += 1 return L>>> fbnq(10)[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]>>> 我们能构建1个list的斐波那契数列,那么generator的怎么构建呢?很简单!
>>> def fbnq(max): # 生成max个元素的斐波那契数列 a, b, n = 0, 1, 0 while n < max: yield b a, b = b , a + b n += 1 >>> fbnq(8)<generator object fbnq at 0x02A1C760>>>> G.next()1>>> G.next()1>>> G.next()2>>> for i in G: print i 3581321>>> 为什么会这样呢?由于有关键字yield,我们构建的第二个函数就不是普通的函数了,而是一个generator。工作原理是:程序执行时,遇到yield就会停下来,并返回当前yield b中的b的值,下次调用时候,又从yield处开始执行,并且执行到下一个yield处暂停,并抛出当前yield b中的b的值。(本例子中有个while循环!)下面是程序运行过程:
>>> def fbnq(max): # 生成max个元素的斐波那契数列 a, b, n = 0, 1, 0 while n < max: print "A" yield b a, b = b , a + b n += 1 print "B" >>> G = fbnq(5)>>> G.next()A1>>> G.next()BA1>>> G.next()BA2>>> G.next()BA3>>> G.next()BA5>>> G.next()BTraceback (most recent call last): File "<pyshell#70>", line 1, in <module> G.next()StopIteration>>>
>>> def fbnq(): a, b = 0, 1 while True: yield a a, b = b , a + b >>> from itertools import islice>>> list(islice(fbnq(), 10))[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]>>>
三、Dictionary and set comprehensions新特性:2.7.X版本及3.2以上版本。本节内容2014.09.25更新。
set和dict表达式
a = {x: x*x for x in range(6)}aOut[9]: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}type(a)Out[10]: dictb = {('a'*x) for x in range(6)}bOut[12]: {'', 'a', 'aa', 'aaa', 'aaaa', 'aaaaa'}type(b)Out[13]: set
Python高级特性之:List Comprehensions、Generator、Dictionary and set ...的更多相关文章
- Python 高级特性介绍 - 迭代的99种姿势 与协程
Python 高级特性介绍 - 迭代的99种姿势 与协程 引言 写这个笔记记录一下一点点收获 测试环境版本: Python 3.7.4 (default, Sep 28 2019, 16:39:19) ...
- 三、python高级特性(切片、迭代、列表生成器、生成器)
1.python高级特性 1.1切片 list列表 L=['Mli','add','sal','saoo','Lkkl'] L[0:3] #即为['Mli','add','sal'] 从索引0开始 ...
- python高级特性:切片/迭代/列表生成式/生成器
廖雪峰老师的教程上学来的,地址:python高级特性 下面以几个具体示例演示用法: 一.切片 1.1 利用切片实现trim def trim(s): while s[:1] == " &qu ...
- Python高级特性(1):Iterators、Generators和itertools(转)
译文:Python高级特性(1):Iterators.Generators和itertools [译注]:作为一门动态脚本语言,Python 对编程初学者而言很友好,丰富的第三方库能够给使用者带来很大 ...
- python高级特性和高阶函数
python高级特性 1.集合的推导式 列表推导式,使用一句表达式构造一个新列表,可包含过滤.转换等操作. 语法:[exp for item in collection if codition] if ...
- Python高级特性(3): Classes和Metaclasses(转)
原文:Python高级特性(3): Classes和Metaclasses 类和对象 类和函数一样都是Python中的对象.当一个类定义完成之后,Python将创建一个“类对象”并将其赋值给一个同名变 ...
- Python高级特性(2):Closures、Decorators和functools(转)
原文:Python高级特性(2):Closures.Decorators和functools 装饰器(Decorators) 装饰器是这样一种设计模式:如果一个类希望添加其他类的一些功能,而不希望通过 ...
- Python高级特性(切片,迭代,列表生成式,生成器,迭代器)
掌握了Python的数据类型.语句和函数,基本上就可以编写出很多有用的程序了. 比如构造一个1, 3, 5, 7, ..., 99的列表,可以通过循环实现: L = [] n = 1 while n ...
- Python高级特性(1):Iterators、Generators和itertools(参考)
对数学家来说,Python这门语言有着很多吸引他们的地方.举几个例子:对于tuple.lists以及sets等容器的支持,使用与传统数学类 似的符号标记方式,还有列表推导式这样与数学中集合推导式和集的 ...
随机推荐
- benchmarks (主要用于分布式文件系统性能测试)
最近进行学习过程中,遇到一些可以用得上的benchmark,在这里进行简要记录:之后估计会用到 TensorFlow benchmarks https://github.com/tensorflow/ ...
- s3c2440裸机-UART编程(二、UART编程实现)
UART编程 1.初始化 我们的2440支持3个UART串口,以uart0为例讲解. 那么我们需要实现以下这几个函数完成串口的最基本功能: (1)uart0_init()用于初始化串口 (2)putc ...
- Java编译器的2点优化
优化1 对于byte/short/char三种类型来说,如果右侧赋值的数值没有超过范围,那么javac编译器将会自动隐含地为我们补上一个(byte)(short)(char). 如果没有超过左侧的范围 ...
- WPF 获取系统 DPI 的多种方法
原文:WPF 获取系统 DPI 的多种方法 WPF 获取系统 DPI 的多种方法 由于 WPF 的尺寸单位和系统的 DPI 相关,我们有时需要获取 DPI 值来进行一些界面布局的调整,本文汇总了一些 ...
- DFS(四):剪枝策略
顾名思义,剪枝就是通过一些判断,剪掉搜索树上不必要的子树.在采用DFS算法搜索时,有时候我们会发现某个结点对应的子树的状态都不是我们要的结果,这时候我们没必要对这个分支进行搜索,砍掉这个子树,就是剪枝 ...
- 抓包工具之fiddler实战1-基本设置
Fiddler概述 百度搜索fiddler能找到官网网站,百度软件中心也提供了下载,本人去下载了基本和官网的版本一致,但还是建议大家下载软件一定去官网进行下载. Fiddler是干什么的 在百度百科里 ...
- 【Linux命令】工作目录切换命令(pwd,cd,ls)
目录 pwd显示当前的工作路径 cd切换工作目录 ls显示目录中文件信息 一.pwd命令 pwd命令用于显示当前的工作路径. 格式: pwd [选项] 参数: -L,--logical,显示当前的路径 ...
- 赖法,强制启动,https版的winrm ---powershell远程连接(winrm)的4个安全级别,详解
---------[winrm的“四级”安全]--------- 四级安全,就是最不安全的. winrm默认使用http+5985端口,密码传输加密,数据.命令传输明文.有被人窃取机密,和插入攻击命令 ...
- [LeetCode#184]Department Highest Salary
The Employee table holds all employees. Every employee has an Id, a salary, and there is also a colu ...
- CSAPP lab3 bufbomb-缓冲区溢出攻击实验(上)smoke fizz
前言 完成这个实验大概花费一天半的时间,看了很多大佬的博客,也踩了很多的坑,于是打算写一篇博客重新梳理一下思路和过程,大概会有两篇博客吧. CSAPP lab3 bufbomb-缓冲区溢出攻击实验(上 ...