美文网首页
Python小记

Python小记

作者: 木月摇江 | 来源:发表于2016-03-14 00:05 被阅读14次

    有些问题,之前看了,也想顺了,理清了。但时间一长又忘了,又得回来重新理一遍,效率很低。这里就记下这些问题和思考后的结论,以免重蹈覆辙。

    2016.3.13

    def countdown(n):
        print("counting down from %d" % n)
        while n>= 0:
            newvalue = yield n
            if not newvalue is None:
                n = newvalue
            else:
                n -= 1
    c = countdown(5)
    for x in c:
        print(x)
        if x == 5:
            c.send(3)
    

    结果为:

    Counting down from 5
    5
    2
    1
    0
    

    解释:

    python的generator的next()和send(),先yield值,在下次执行yield后面的语句前,yield表达式先返回结果,对于send()返回传入的参数,next()返回None,然后继续实行yield后的代码。

    分析:

    有上面的解释,可以分析出由for...in...启动generator,第一次yield值为5,执行c.send(5),此时newvalue被赋值为3,接着n也被赋值3,再次yield返回for...in...,再由next()进入generator,在上一次yield处,newvalue现在被赋值None,那么此时n减1变成2,执行到yield返回n值2。后面就以此类推。

    关于send函数的官方说明:

    Resumes the execution and "sends'' a value into the generator function. The value argument becomes the result of the current yield expression. The send() method returns the next value yielded by the generator, or raises StopIteration if the generator exits without yielding another value. When send() is called to start the generator, it must be called with None as the argument, because there is no yield expression that could receive the value.

    2016.3.21

    再过几个小时Apple就要开发布会了,看来今天晚上要熬夜了。但是学习还是要继续的。记一下Python中and,or返回值的感人之处:

    Python中and和or返回的返回值确切来说不是直接的布尔值,而是以比较情况返回它们比较的值中的一个;同时and和or还有短路的性质。

    先看一下and:

    a = 'first'
    b = 'second'
    names = ['Michael', 'Jack', 'Bob', 'Tracy']
    >>> a and b
    'second'
    >>> '' and b
    ''
    >>> a and b and 'c'
    'c'
    >>> True and names.pop()
    ['Michael', 'Jack', 'Bob']
    >>> False and names.pop()
    ['Michael', 'Jack', 'Bob', 'Tracy']
    

    可以看出,and从左向右,逐一判断比较的值,如果所有比较的值都可以判为True,那么and返回最后一个比较的值;一旦遇到可判为False的值and立即返回该值,不再比较后面的值,如果后面有操作也就无法执行到了。

    再看一下or:

    a = 'first'
    b = 'second'
    names = ['Michael', 'Jack', 'Bob', 'Tracy']
    >>> a or b
    'first'
    >>> '' or b
    'second'
    >>> '' and [] and ()
    ()
    >>> '' and a and b
    'first'
    >>> False or names.pop()
    ['Michael', 'Jack', 'Bob']
    >>> True or names.pop()
    ['Michael', 'Jack', 'Bob', 'Tracy']
    

    可以看出,or从左向右,逐一判断比较的值,如果所有比较的值都可以判为False,那么or返回最后一个比较的值;一旦遇到可判为True的值or立即返回该值,不再比较后面的值,如果后面有操作也就无法执行到了。

    最后看一下and-or:

    >>> a='first'
    >>> b='second'
    >>> 1 and a or b
    'first'
    >>> (1 and a) or b
    'first'
    >>> 0 and a or b
    'second'
    >>> (0 and a) or b
    'second'
    

    这个没有什么了,and-or混合的时候,判断顺序还是从左向右,先执行一个运算符,其结果作为下个运算符的比较值,结合上面两条结果很容易可以推出来了。

    2016.6.15

    Python居然没有三元运算符,只能“曲线救国”用下面的方式来代替了:

    [true_operation] if [condition] else [false_operation]
    

    相关文章

      网友评论

          本文标题:Python小记

          本文链接:https://www.haomeiwen.com/subject/rylflttx.html