python-对于yield 的理解

In Python 3, there are a lot of difference compared to python2 .  So in this part, I'll talk about the yield 

 

1、Function contains yield

def h():
    print ('To be brave')
    yield 5

h()

(1)it's not the result we want

(2) How  to understand the priciple of the  yield

def h():
    print ('Wen Chuan')
    yield 5
    print ('Fighting!')

c = h()
next(c)

 It will connitune working untill   yield 5   so  the result will be  'Wen Chuan '    

Because there arennot any yield after that, so there will be an exception 

 

2.、send(msg) and next()

For next , we  cannot give another parameter , so   we use next(h)   , As for send , basicly  c.send(None)= next(c)   

 

So that's how we use ,

 

 

3、 About the returned value of yield

 

4、throw() and close()    interrupt Generator

the content below is the understanding of close()

 

 

 

5、My understanding

When you have yield   in the function, we have to 把 它实例化 之后进行使用

def factorial(n):
    for i in n :
        yield (i*i)




num=[1,2,3,4,5]
myni=factorial(num)
print(factorial(num))
print(next(myni))
print(next(myni))
print(next(myni))
print(next(myni))
print(next(myni))



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
yield函数是一个生成器(generator),它可以用于迭代。在函数中,yield类似于return,不同的是,yield返回一个值并且记住这个返回值的位置,下次迭代就从记住的位置开始执行,并且从上一次迭代遇到的yield后面的代码开始执行。 yield函数的优点在于它可以减少内存的消耗,因为它不直接生成返回值。相比使用return返回值或者迭代大量数据,yield函数能够更好地减少内存消耗。然而,由于yield函数只能读取一次,所以它的特点是只能迭代一次。 yield函数不仅可以用于for循环,还可以作为函数参数。例如,可以将yield函数作为其他函数的参数传递,实现更加灵活的功能。 除了next()函数之外,还有一个特别的函数叫做send()函数。send()函数的特点是可以携带参数,并且可以修改上一个yield表达式的值。使用方式与next()函数有很多相似之处。<span class="em">1</span><span class="em">2</span><span class="em">3</span><span class="em">4</span> #### 引用[.reference_title] - *1* *2* *3* *4* [Python|yield的解析及用法](https://blog.csdn.net/gschen_cn/article/details/107293784)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

没有水杯和雨伞的工科男

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值