24day

1、列表生成式:

循环模式:[变量(加工后的变量) for 变量 in iterable]

print([i for i in range(0,101,2)])
[1,4,9,16,25,36,49]
print([i*i for i in range(1,8)])
#['python1期', 'python2期', .....'python20期']
print(['python%s期'%i for i in range(1,21)])

筛选模式:[变量(加工后的变量) for 变量 in iterable if 条件]

[变量(加工后的变量) for 变量 in iterable if 条件]
print([i for i in range(1,31) if i % 3 == 0])
print([i for i in range(1,31) if i % 3 == 0])
30以内能被2整除的数的平方
print([ i*i for i in range(1,31) if i % 2 == 0])
[1,2,3,4,6,7,8]
print([i for i in range(1,9)if i != 5])
l1 = ['wusir','ba', 'aa' ,'alex']
过滤掉长度小于3的字符串列表,并将剩下的转换成大写字母
print([i.upper() for i in l1 if len(i) > 3])
['WUSIR','ALEX']
names = [['Tom', 'Billy', 'Jefferson', 'Andrew', 'Wesley', 'Steven', 'Joe'],
['Alice', 'Jill', 'Ana', 'Wendy', 'Jennifer', 'Sherry', 'Eva']]
将列表中的至少含有两个'e'的人名留下来。
l1 = []
for l in names: #正常情况
for name in l:
if name.count('e') >= 2:
l1.append(name)
print(l1)
print([j for i in names for j in i if j.count('e')==2])  #列表生成式

 >>> a = [i+1 for i in range(10)]
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> a = [i+1 for i in range(10)]
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> a = [i+1 for i in a]
>>> a
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
>>> a = [i+1 for i in a]
>>> a
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

通过列表生成式,我们可以直接创建一个列表

2、生成器:generator

生成器特性:

- 不占内存

- 只能向前,不能返回

- 当生成器达到要求会报错

创建generator,方法一:一个列表生成式的[]改成(),就创建了一个generator

>>> a3 = (i for i in range(5))
>>> a3
<generator object <genexpr> at 0x0000000001DF5BA0>
>>> next(a3)
0
>>> next(a3)
1
>>> next(a3)
2
>>> next(a3)
3
>>> next(a3)
4
>>> next(a3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration

通过for循环来调用生成器

>>> a3 = (i for i in range(5))
>>> for i in a3:
... print(i)
...
0
1
2
3
4

通过while循环来调生成器(跳出循环会报错)

>>> a3 = (i for i in range(5))
>>> while True:
... next(a3)
...
0
1
2
3
4
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
StopIteration

方法二:使用yield创建生成器(一个函数中包含yield关键字,那么这个函数就不在是一个普通的函数,而是一个generator)

generator和函数不一样。函数是按顺序执行,遇到return语句或最后一行函数语句就返回。而变成generator的函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时会从上一次返回的yield语句处继续执行。

return VS yield

return :返回并中止function

yield :返回数据,并冰冻当前的执行过程。next唤醒冻结的函数执行过程,直到遇到下一个yield

 def fib(max):
n,a,b = 0,0,1
while n < max:
yield b #把函数的执行过程冻结在这一步,并且把b的值,返回给外面的next
print(b)
a,b = b,a+b
n += 1
return 'done' f = fib(10)
next(f)
next(f)
next(f)

当函数里面存在同时存在yield和return时,return值无法返回

 def range2(n):
count = 0
while count < n:
print('count',count)
count += 1
yield count
return 33333 new_range = range2(3)
n1 = next(new_range)
n2 = next(new_range)
n3 = next(new_range)
n4 = next(new_range)

#执行结果如下

Traceback (most recent call last):
count 0
count 1
count 2
File "D:/编辑的文本/生成器.py", line 27, in <module>
n4 = next(new_range)
StopIteration: 33333

3、生成器send

 def range2(n):
count = 0
while count < n:
print('count',count)
count += 1
sign = yield count
print('sign',sign)
return 33333 new_range = range2(3)
n1 = next(new_range)
new_range.send('stop')

#执行结果:

count 0
sign stop
count 1

send------>>>>a、唤醒并继续执行;b、发送一个信息到生成器内部;

总结:

列表推导式 与生成器表达式区别;
1,列表推导式 一行搞定,构建简单。
2, 不能用debug排错,比较复杂的列表列表推导式不能推导出来。 生成器表达式:
1,循环模式。 (变量(加工后的变量) for 变量 in iterable)
(变量(加工后的变量) for 变量 in iterable if 条件)
1,一行搞定。
2,节省内存。

Python初学者第二十四天 函数进阶(3)生成器的更多相关文章

  1. python学习三十四天函数高阶函数定义及用法

    python函数高阶函数是把函数当成一个变量,传递给函数作为参数,或者函数的返回值里面有函数,都称为高阶函数, 1,把函数作为参数传递 def dac(x,y): return x+y def tes ...

  2. python设计模式第二十四天【命令模式】

    1.使用场景 (1)调用过程比较繁琐,需要封装 (2)调用参数需要进行处理封装 (3)需要添加额外的功能,例如,日志,缓存,操作记录等 2.代码实现 #!/usr/bin/env python #! ...

  3. python学习第二十五天函数位置参数和关键词参数

    函数位置参数顾名思义就是按位置排序,按位置对应参数,位置一一对应,函数的关键词参数是不按照顺序来的,可以指定的参数传值.但是注意的是,位置参数必须在关键词参数之前. 1,函数位置参数 def good ...

  4. python学习二十四天函数参数之默认参数

    函数参数就是向函数传递参数,可以传递一个,可以是更多个,有的参数有值,有的没有,函数可以设置默认参数,默认参数必须放参数最后面. 1,不传递参数,设置默认参数 def hello(a,b,c='123 ...

  5. Python初学者第十四天 三元运算及文件处理2

    14day 1.三元运算: 又称三目运算,是对简单的条件语句的简写 如简单条件语句: if a > b: n = a else: n = b print(n) 三目运算语句: n = a if ...

  6. Python学习第二十四课——Mysql 外键约束

    外键:主要是关联两个表的 举个栗子:在建表中创建外键 -- 添加外键例子 CREATE TABLE teacher( id TINYINT PRIMARY KEY auto_increment, na ...

  7. 孤荷凌寒自学python第二十四天python类中隐藏的私有方法探秘

    孤荷凌寒自学python第二十四天python类中隐藏的私有方法探秘 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 今天发现了python的类中隐藏着一些特殊的私有方法. 这些私有方法不管我 ...

  8. Python第二十四天 binascii模块

    Python第二十四天 binascii模块 binascii用来进行进制和字符串之间的转换 import binascii s = 'abcde' h = binascii.b2a_hex(s) # ...

  9. 孤荷凌寒自学python第七十四天开始写Python的第一个爬虫4

    孤荷凌寒自学python第七十四天开始写Python的第一个爬虫4 (完整学习过程屏幕记录视频地址在文末) 今天在上一天的基础上继续完成对我的第一个代码程序的书写. 直接上代码.详细过程见文末屏幕录像 ...

随机推荐

  1. Linux-(chgrp,chown,chmod)

    /etc/group Linux /etc/group文件与/etc/passwd和/etc/shadow文件都是有关于系统管理员对用户和用户组管理时相关的文件. Linux /etc/group文件 ...

  2. ArrayList的subList方法

    参考博文使用java.util.List.subList时最好小心点 List接口中定义: List<E> subList(int fromIndex, int toIndex); 英文注 ...

  3. Django 多表查询

    多表查询是模型层的重要功能之一, Django提供了一套基于关联字段独特的解决方案. ForeignKey 来自Django官方文档的模型示例: from django.db import model ...

  4. IOS bug之cannot be opened because the project file cannot be parsed

    刚才用Cornerstone更新代码后,再次打开项目时,不能打开,提示cannot be opened because the project file cannot be parsed后来在网上查了 ...

  5. 转载:SQL中的case when then else end用法

    SQL中的case when then else end用法 来源: http://www.cnblogs.com/prefect/p/5746624.html Case具有两种格式.简单Case函数 ...

  6. Java基础教程(20)--数字和字符串

    一.数字   在用到数字时,大多数情况下我们都会使用基本数据类型.例如: int i = 500; float gpa = 3.65f; byte mask = 0xff;   然而,有时候我们既需要 ...

  7. 解决post请求乱码问题

    将下面配置信息配置在webapp/WEB-INF/web.xml中 <!-- 解决post乱码 --><filter> <filter-name>Character ...

  8. java基础之运算符与语句

    一.运算符 1.算数运算符 运算符 名称 举例 + 加法 A等于10,B等于3 则A+B=13 - 减法 A等于10,B等于3 则A-B=7 * 乘法 A等于10,B等于3 则A*B=30 / 除法 ...

  9. 【5】Builder模式(构建者模式)

    一.引言 在软件系统中,有时需要创建一个复杂对象,并且这个复杂对象由其各部分子对象通过一定的步骤组合而成.例如一个采购系统中,如果需要采购员去采购一批电脑时,在这个实际需求中,电脑就是一个复杂的对象, ...

  10. Code Signal_练习题_Make Array Consecutive2

    Description Ratiorg got statues of different sizes as a present from CodeMaster for his birthday, ea ...