yield

可迭代对象、迭代器和生成器

那年仲夏 提交于 2019-11-29 14:59:12
迭代(Iteration) ​ 当我们使⽤⼀个循环来遍历某个东西时,这就叫⼀个迭代。 可迭代对象(Iterable) ​ ⼀个可迭代对象是Python中任意的对象,只要它定义了可以返回⼀个迭代器的 __iter__ ⽅法,或者定义了可以⽀持下标索引的 __getitem__ ⽅法。简单说,⼀个可迭代对象,就是任意的对象,只要它能给我们提供⼀个迭代器。 container__iter__() 返回一个迭代器对象 。 该对象需要支持迭代器协议。 如果容器支持不同的迭代类型,则可以提供额外的方法来专门地请求不同迭代类型的迭代器。 迭代器(Iterator) ​ ⼀个迭代器是任意⼀个对象,只要它定义了⼀个next(Python2) 或者 __next__ ⽅法。 iterator.__next__() 从容器中返回下一项。 如果已经没有项可返回,则会引发 StopIteration 异常。 特点: 节省内存,惰性机制,不能反复, 只能向下执行. 迭代器是可迭代的,所有的迭代器都是它们自己的迭代器 迭代器没有长度,它们不能被索引 可以把迭代器看作是 惰性迭代器 ,它们是 一次性使用 ,这意味着它们只能循环遍历一次。 文件迭代器 #手动遍历 f = open('xxx','r',encoding='utf8') f.readline() #每次调用readine方法,就会到下一列

What does the new keyword “yield” mean in Java 13?

谁说我不能喝 提交于 2019-11-29 14:00:11
问题 Java 13 introduced the yield keyword for switch expressions. How can I use it and what's the difference to a default return or break value? 回答1: Q&A How can I use it? With arrow labels when a full block is needed: int value = switch (greeting) { case "hi" -> { System.out.println("I am not just yielding!"); yield 1; } case "hello" -> { System.out.println("Me too."); yield 2; } default -> { System.out.println("OK"); yield -1; } }; With traditional blocks: int value = switch (greeting) { case

Using yield to iterate over a datareader might not close the connection?

浪子不回头ぞ 提交于 2019-11-29 11:44:41
问题 Here is a sample code to retrieve data from a database using the yield keyword that I found in a few place while googling around : public IEnumerable<object> ExecuteSelect(string commandText) { using (IDbConnection connection = CreateConnection()) { using (IDbCommand cmd = CreateCommand(commandText, connection)) { connection.Open(); using (IDbDataReader reader = cmd.ExecuteReader()) { while(reader.Read()) { yield return reader["SomeField"]; } } connection.Close(); } } } Am I correct in

Serialization and the Yield statement

微笑、不失礼 提交于 2019-11-29 11:41:57
问题 Is it possible to serialize a method containing yield statements (or a class that contains such a method) such that when you rehydrate the class, the internal state of the generated iterator is retained? 回答1: Yes, you can do this. With caveats. An example of serializing a method with a yield , deserializing and continuing can be found here: http://www.agilekiwi.com/dotnet/CountingDemo.cs (Web Archive Link). In general, trying to serialize without doing some extra work will fail. This is

python笔记14—day14

江枫思渺然 提交于 2019-11-29 11:34:34
1、生成器函数进阶 1.1、send def generator(): print(123) content = yield 1 print('=======',content) print(456) arg = yield 2 g = generator() ret = g.__next__() print('***',ret) ret = g.send('hello') #send的效果和next一样 print('***',ret) #结果: #123 #*** 1 #======= hello #456 #*** 2 send 获取下一个值的效果和next基本一致 只是在获取下一个值的时候,给上一yield的位置传递一个数据 使用send的注意事项   第一次使用生成器的时候 是用next获取下一个值   最后一个yield不能接受外部的值 1.2、移动数据求平均值 def average(): sum = 0 count = 0 avg = 0 while True: num = yield avg sum += num # 10 count += 1 # 1 avg = sum/count avg_g = average() avg_g.__next__() avg1 = avg_g.send(10) avg1 = avg_g.send(20) avg1=avg_g

生成器和迭代器

岁酱吖の 提交于 2019-11-29 11:30:18
列表生成式     >>> a = [i+1 for i in range(10)]     >>> a     [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]     循环 range(10) 生成一个列表,这就是列表生成器        这个range() 函数可创建一个整数列表        python2 : /*--> */ /*--> */         >>> print(range(10))         [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]     python3 : /*--> */ /*--> */         >>> print(range(10))         range(0, 10)             以上可见python2中,等于是创建了两个列表,比python3中,增加了内存消耗,python3中的优化        生成器generator       由上可知在python2中,创建一个包含100万个元素的列表,不仅占用很大的存储空间,     如果我们仅仅需要访问前面几个元素,那后面绝大多数元素占用的空间都白白浪费了。比如我要循环100万次,     按py的语法,for i in range(1000000)会先生成100万个值的列表。但是循环到第50次时,     我就不想继续了

What is the equivalent syntax in VB.NET for “yield return”? [duplicate]

巧了我就是萌 提交于 2019-11-29 11:20:40
This question already has an answer here: Yield in VB.NET 8 answers Using the C# code below, how would you write it in Visual Basic? What is it trying to say? using System; using System.Collections.Generic; using System.IO; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; namespace Microsoft.LiveLabs.Pivot { /// <summary> /// Tile Builder class /// </summary> public static class TileBuilder { /// <summary> /// Specifies which images are required in the images array used in CreateTile /// according to the Morton fractal pattern used by Seadragon. /// <

生成器

元气小坏坏 提交于 2019-11-29 11:19:05
什么是生成器: 通过列表生成式,我们可以直接创建一个列表,但是,受到内存限制,列表容量肯定是有限的,而且创建一个包含100万个元素的列表,不仅占用很大的存储空间,如果我们仅仅需要访问前面几个元素,那后面绝大多数元素占用的空间都白白浪费了。   所以,如果列表元素可以按照某种算法推算出来,那我们是否可以在循环的过程中不断推算出后续的元素呢?这样就不必创建完整的list,从而节省大量的空间,在Python中,这种一边循环一边计算的机制,称为生成器:generator。   生成器是一个特殊的程序,可以被用作控制循环的迭代行为,python中生成器是迭代器的一种,使用yield返回值函数,每次调用yield会暂停,而可以使用next()函数和send()函数恢复生成器。   生成器类似于返回值为数组的一个函数,这个函数可以接受参数,可以被调用,但是,不同于一般的函数会一次性返回包括了所有数值的数组,生成器一次只能产生一个值,这样消耗的内存数量将大大减小,而且允许调用函数可以很快的处理前几个返回值,因此生成器看起来像是一个函数,但是表现得却像是迭代器。 创建列表,直接在内存生成,不管调不调用,都占用内存空间。而创建生成器,只有调用时,才会在内存生成。 列表和生成器的区别在于最外层,最外层为[]时为列表,最外层为()时为生成器generator 列表如下>>>[i*2 for i in

Splitting textfile into section with special delimiter line - python

谁说我不能喝 提交于 2019-11-29 11:14:18
I have an input file as such: This is a text block start This is the end And this is another with more than one line and another line. The desired task is to read the files by section delimited by some special line, in this case it's an empty line, e.g. [out]: [['This is a text block start', 'This is the end'], ['And this is another','with more than one line', 'and another line.']] I have been getting the desired output by doing so: def per_section(it): """ Read a file and yield sections using empty line as delimiter """ section = [] for line in it: if line.strip('\n'): section.append(line)

python里的生成器--yield

為{幸葍}努か 提交于 2019-11-29 10:48:30
Python的生成器是个很强大的东西,特别是在python3.0版本以后。以最简单的方式让大家快速理解生成器。 1、正常的写法 来看个例子,比如输出一个自定义长度的列表一般这么写: 这里传入的参数时10,所以会得到一个包含10个元素的列表: 那当我传入的是10W的时候,那生成的这个列表就很大了,也占内存,运行脚本也占cpu。 2、改良后写法 改良一下代码,把他写成一个迭代的类: 这里面self.b就记录了每次执行next方法的位置,知道每次是第几次执行next方法,所以执行保证了每次输出的是期望的值,其实这就是迭代了,每运行一次函数都被记录已运行的状态。当被调用的时候才返回值,否则就处于等待被调用的状态 运行结果: 所以这改良后的代码就解决了当你输入10W的时候占用资源的问题,因为输入10W后,只要当调用next函数的时候才返回值,不是一次返回一个那么大的列表出来。 3、生成器 那么第二步中的代码跟第一步比起来又太多了感觉,那么生成器就来了 再改良代码: 只需改下第一步中的代码a.append(n)为yield n,这就是一个生成器了,然后通过for语句来调用生成器的值。 任何一个带有yield语句的函数都是生成器,当你直接调用这个函数时,内部的代码是不会被执行的,只有调用yield里面的next函数才会去执行代码,for循环也就是会自动去调用这个next函数来输出值。