十三. Python基础(13)--生成器进阶 1 ● send()方法 generator.send(value) Resumes the execution, and "sends" a argument which becomes the result of the current yield expression in the generator function. The send() method, like __next__(), returns the next v…
十二. Python基础(12)--生成器 1 ● 可迭代对象(iterable) An object capable of returning its members one at a time. Examples of iterables include all sequence types (such as list, str, and tuple) and some non-sequence types like dict and file and objects of any clas…
1 生成器: 为什么要有生成器? 就拿列表来说吧,假如我们要创建一个list,这个list要求格式为:[1,4,9,16,25,36……]这么一直持续下去,直到有了一万个元素的时候为止.如果我们要创建这个list,那么应该是这样的: [i*i for i in range(1,10001)] #列表生成式,不要忘了 #结果就不列出来了 这样的话,这个list会占用极多的内存,如果我们能只将算法保存在list中,那么这个list所占的内存会大大减小,等我们需要用到list的值的时候,这个list会…
目录: 生成器 迭代器 模块 time 序列化 反序列化 日志 一.生成器 列表生成式: a = [1,2,3,3,4,5,6,7,8,9,10] a = [i+1 for i in a ] print(a) a = [i*1 if i > 5 else i for i in a] print(a) 生成器:generator 不能事先把元素全部加载到内存,可以是边使用边生成的方式来依次获取元素: 生成器的使用方法: 列表生成式生成的是列表: 将列表生成器中的[]改成()就成为了一个生成器: 示…
一.列表生成式 用来创建list的表达式,相当于for循环的简写形式 语法: [表达式 for循环 判断条件] ''' 普通写法 ''' def test(): l= [] for i in range(10): l.append(i*i) return l print(test()) ''' 高级写法 ''' l = [x * x for x in range(10)] print(l) ''' 更高级的用法 格式:[操作 for i in range(x) 执行操作的条件(x)] ''' #…
Python迭代器和生成器 1.迭代器 迭代:可以将某个数据集内的数据“一个挨着一个的取出来” for i in range(1, 10, 2): # in 后面的对象必须是一个可迭代的 print(i) # 从可迭代对象中将元素一个一个取出 """ 判断是否可迭代 """ from collections import Iterable str1 = 'adc' l = [1, 2, 3, 4] t = (1, 2, 3, 4) d = {1:…