yield

python中迭代器和生成器的简单介绍

社会主义新天地 提交于 2019-12-03 03:30:54
# -*- coding: utf-8 -*- """ 迭代器和生成器 迭代器:类型list、tuple、file、dict的对象有__iter__()方法,标志着它们能够迭代 用__iter__()方法生成迭代对象,然后用__next__()方法访问 生成器:是迭代器,__iter__()和next();针对大数据的时候,Python处理列表时,将全部数据都读入到内存,而 迭代器(生成器是迭代器)的优势就在于只将所需要的读入内存里,因此生成器解析式比列表解析式少占内存 一个简单的生成器my_generator = (x*x for x in range(4)) yield:生成器的标志,yield除了作为生成器的标志之外,还有一个功能就是返回值;作为生成器的函数, 由于有了yield,遇到它则程序挂起 yield和return的区别:return返回后,程序后面的语句不执行,yield返回后,程序挂起,再次调用__next__()时,继续执行后面的语句 """ class MyIter: '''简单的range迭代器实现''' def __init__(self,n): self.i=0 self.n=n def __iter__(self): '''__iter__()是类中的核心,它返回了迭代器本身,实现了__iter__()方法的对象,即意味着其可迭代''' print(

python3迭代器和生成器

梦想的初衷 提交于 2019-12-03 03:30:16
迭代器: 访问集合元素的一种方式。 字符串,列表或元组对象 都可用于创建迭代器。 for i in 10: print(i) 即:int类型不可以 迭代器: 可以记住遍历的对象的上一次位置; 从集合的第一个元素开始访问,直到所有的元素被访问结束。 即:只能往前不会后退。 for i in range(10): print(i) 如图: 手动创建: items = [0,1,2,3,4,5,6] #it:迭代器 it = list(iter(items)) print(it) 如图: 自定义迭代器: 内建函数 iter()可以从 可迭代对象中获得迭代器。 可迭代对象: list tuple dict str set class Container: def __init__(self,start,end): self.start=start self.end=end def __iter__(self): print('调用了 __iter__(self) 方法') return self #返回迭代器 对象本身 def __next__(self): ''' self.start 即时开始位置也是记录位置的状态 :return: ''' if self.start<self.end: i = self.start self.start = self.start+1 return i

python之迭代器与生成器

試著忘記壹切 提交于 2019-12-03 03:23:09
python之迭代器与生成器 可迭代 假如现在有一个列表,有一个int类型的12345。我们循环输出。 list=[1,2,3,4,5] for i in list: print(i) for i in 12345: print(i) 结果: Traceback (most recent call last): File "C:/Pycham/生成器与迭代器/test1.py", line 6, in <module> for i in 12345: TypeError: 'int' object is not iterable 1 2 3 4 5 报错显示:1234不是可以被迭代的。 那python中哪些是 可迭代 的:字符串、列表、元组、字典、集合。 for循环工作机制:for循环在循环一个对象的时候,会调用这个对象的iter方法,得到迭代器,然后在调用这个迭代器的next方法,去获得这个迭代器中包涵的每个值。 现在可能我们不太明白,什么是iter方法,什么是迭代器,什么是next方法。    迭代器 但是如果只是将数据集内的数据“一个挨着一个的取出来,for循环就可以做到,为什么要使用迭代器呢?迭代器是什么? 迭代器能迭代的一定是可以迭代的数据类型。 如果我们要使用迭代器,一定要将可以被迭代的数据集转为迭代器,使用 __iter__() 。    #列表生成式 list=[1

Is it possible to use 'yield' to generate 'Iterator' instead of a list in Scala?

倾然丶 夕夏残阳落幕 提交于 2019-12-03 03:08:05
问题 Is it possible to use yield as an iterator without evaluation of every value? It is a common task when it is easy to implement complex list generation, and then you need to convert it into Iterator , because you don't need some results... 回答1: Sure. Actually, there are three options for non-strictness, which I list below. For the examples, assume: val list = List.range(1, 10) def compute(n: Int) = { println("Computing "+n) n * 2 } Stream . A Stream is a lazily evaluated list. It will compute

what's the difference between yield from and yield in python 3.3.2+

蓝咒 提交于 2019-12-03 03:02:50
After python 3.3.2+ python support a new syntax for create generator function yield from <expression> I have made a quick try for this by >>> def g(): ... yield from [1,2,3,4] ... >>> for i in g(): ... print(i) ... 1 2 3 4 >>> It seems simple to use but the PEP document is complex. My question is that is there any other difference compare to the previous yield statement? Thanks. For most applications, yield from just yields everything from the left iterable in order: def iterable1(): yield 1 yield 2 def iterable2(): yield from iterable1() yield 3 assert list(iterable2) == [1, 2, 3] For 90% of

May a while loop be used with yield in scala

孤者浪人 提交于 2019-12-03 02:33:53
Here is the standard format for a for/yield in scala: notice it expects a collection - whose elements drive the iteration. for (blah <- blahs) yield someThingDependentOnBlah I have a situation where an indeterminate number of iterations will occur in a loop. The inner loop logic determines how many will be executed. while (condition) { some logic that affects the triggering condition } yield blah Each iteration will generate one element of a sequence - just like a yield is programmed to do. What is a recommended way to do this? You can Iterator.continually{ some logic; blah }.takeWhile

python【5】迭代,生成,修饰

不问归期 提交于 2019-12-03 01:49:40
迭代器 迭代器是访问集合元素的一种方式。迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退,不过这也没什么,因为人们很少在迭代途中往后退。另外,迭代器的一大优点是不要求事先准备好整个迭代过程中所有的元素。迭代器仅仅在迭代到某个元素时才计算该元素,而在这之前或之后,元素可以不存在或者被销毁。这个特点使得它特别适合用于遍历一些巨大的或是无限的集合,比如几个G的文件 特点: 访问者不需要关心迭代器内部的结构,仅需通过next()方法不断去取下一个内容 不能随机访问集合中的某个值 ,只能从头到尾依次访问 访问到一半时不能往回退 便于循环比较大的数据集合,节省内存 from collections import Iterator # isinstance() 判断是否是 迭代器# 可以被next()函数不断返还下一个值的被称为迭代器# iter() 可以将 list dict str 编程迭代器 生成器generator 定义:一个函数调用时返回一个迭代器,那这个函数就叫做生成器(generator),如果函数中包含yield语法,那这个函数就会变成生成器 #!/usr/bin/env python # -*- coding: utf-8 -*- # By Garrett a = [i*2 for i in range(10)] print(a) #

Python, SimPy: Using yield inside functions

匿名 (未验证) 提交于 2019-12-03 01:36:02
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 问题: Helo, I'm building a relatively complex Discrete Event Simulation Model in SimPy. When I try to put my yield statements inside functions, my program doesn't seem to work. Below shows an example. import SimPy.SimulationTrace as Sim import random ## Model components ## class Customer(Sim.Process): def visit(self): yield Sim.hold, self, 2.0 if random.random()<0.5: self.holdLong() else: self.holdShort() def holdLong(self): yield Sim.hold, self, 1.0 # more yeild statements to follow def holdShort(self): yield Sim.hold, self, 0.5 # more yeild

C# 中yield关键字解析

筅森魡賤 提交于 2019-12-03 01:34:34
前言   前段时间了解到 yield关键字,一直觉得还不错。今天给大家分享一下yield关键字的用法。yield return 返回集合不是一次性返回所有集合元素,而是一次调用返回一个元素。具体如何使用yield return 返回集合呢?我们一起往下面看吧。 yield使用介绍 yield return 和yield break: 我们看下平常循环返回集合的使用操作(返回 1-100中的偶数): class Program { static private List<int> _numArray; //用来保存1-100 这100个整数 Program() //构造函数。我们可以通过这个构造函数往待测试集合中存入1-100这100个测试数据 { _numArray = new List<int>(); //给集合变量开始在堆内存上开内存,并且把内存首地址交给这个_numArray变量 for (int i = 1; i <= 100; i++) { _numArray.Add(i); //把1到100保存在集合当中方便操作 } } static void Main(string[] args) { new Program(); TestMethod(); } //测试求1到100之间的全部偶数 static public void TestMethod() { foreach

How can I traverse a file system with a generator?

笑着哭i 提交于 2019-12-03 01:19:44
I'm trying to create a utility class for traversing all the files in a directory, including those within subdirectories and sub-subdirectories. I tried to use a generator because generators are cool; however, I hit a snag. def grab_files(directory): for name in os.listdir(directory): full_path = os.path.join(directory, name) if os.path.isdir(full_path): yield grab_files(full_path) elif os.path.isfile(full_path): yield full_path else: print('Unidentified name %s. It could be a symbolic link' % full_path) When the generator reaches a directory, it simply yields the memory location of the new