python复习

Python允许你同时为多个变量赋值。例如:

a = b = c = 1

您也可以为多个对象指定多个变量。例如:

a, b, c = 1, 2, "runoob"

不忘初心继续练习算法.
据说是今日头条的面试题.明天面试头条今天赶紧做做
leetcode114
114. 二叉树展开为链表# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def flatten(self, root):
        """
        :type root: TreeNode
        :rtype: void Do not return anything, modify root in-place instead.
        """
        def qianxu(root):
            if root==None:
                return []
           

            return [root]+qianxu(root.left)+qianxu(root.right)
        a=qianxu(root)
        for i in range(len(a)-1):
            a[i].right=a[i+1]
            a[i].left=None
        

构造函数 dict() 可以直接从键值对序列中构建字典如下:

实例

>>>dict([('Runoob', 1), ('Google', 2), ('Taobao', 3)]) {'Taobao': 3, 'Runoob': 1, 'Google': 2}
>>> dict(Runoob=1, Google=2, Taobao=3) {'Taobao': 3, 'Runoob': 1, 'Google': 2}
 
 
break的高级实用:

总之:一句话:else 在循环体里面表示如果不是从break退出就运行这个else.!!!!!!!把语法扣细

 迭代器:

生成器:上面代码. 就是用yield 和next

 迭代器就是用iter 和next

迭代器很简单:

生成器这样理解:运行next(f) ,那么函数就开始运行然后运行到yield,就退出,yield的值就是next这个函数的返回值.然后下次运行next就从上一次yield

停止的地方继续运行. 非常牛逼的功能,这个暂停再运行 不就是我们多进程需要的功能么.多进程可以用yield来模拟.效果很好.

 全局变量测底复习:global 和nonlocal 
def outer():
    num = 10
    def inner():
        global num   # nonlocal关键字声明
        num = 100
        print(num)
    inner()
    print(num)
outer()


def outer():
    num = 10
    def inner():
        nonlocal num   # nonlocal关键字声明
        num = 100
        print(num)
    inner()
    print(num)
outer()
View Code
原文地址:https://www.cnblogs.com/zhangbo2008/p/9201538.html