• Python 中的那些坑总结——持续更新


    1.三元表达式之坑

    很显然,Python把第一行的(10 + 4)看成了三元表达式的前部分,这个坑是看了《Python cookbook》(P5)中学到的,书中的代码:

    2.Python生成器(yield)+递归

    前两天一直纠结python的生成器递归该怎么写,今天看了os.walk()的代码恍然大悟,编程真是博大精深啊!不多说,上代码:

    from os import path
    
    def walk(top, topdown=True, onerror=None, followlinks=False):
        islink, join, isdir = path.islink, path.join, path.isdir
        try:
            # Note that listdir and error are globals in this module due
            # to earlier import-*.
            names = listdir(top)
        except error, err:
            if onerror is not None:
                onerror(err)
            return
    
        dirs, nondirs = [], []
        for name in names:
            if isdir(join(top, name)):
                dirs.append(name)
            else:
                nondirs.append(name)
    
        if topdown:
            yield top, dirs, nondirs
        for name in dirs:
            new_path = join(top, name)
            if followlinks or not islink(new_path):
                for x in walk(new_path, topdown, onerror, followlinks):  # 生成器递归
                    yield x
        if not topdown:
            yield top, dirs, nondirs

    3.try...finally + return:

      如果写了try模块内有return且最后还有finally,那么会执行return后再执行finally。

      这是从Queue的get方法里看到的,贴上自己写的测试代码:

      

      附加Queue的get方法:

    # Queue.py
    ......
        def get(self, block=True, timeout=None):
            self.not_empty.acquire()
            try:
                if not block:
                    if not self._qsize():
                        raise Empty
                elif timeout is None:
                    while not self._qsize():
                        self.not_empty.wait()
                elif timeout < 0:
                    raise ValueError("'timeout' must be a non-negative number")
                else:
                    endtime = _time() + timeout
                    while not self._qsize():
                        remaining = endtime - _time()
                        if remaining <= 0.0:
                            raise Empty
                        self.not_empty.wait(remaining)
                item = self._get()
                self.not_full.notify()
                return item
            finally:
                self.not_empty.release()
  • 相关阅读:
    C#代码中函数调用相关问题
    C#语言编写代码时常用的三大循环
    c#语言中的类型转换
    tesseract_vs2015工具包使用
    Halcon除法
    halcon批量读取图片
    halcon分离路径名称
    Halcon旋转图片的研究
    关于Haclon使用GPU加速的代码实例
    OpenCV代码:画出轮廓的外接矩形,和中心点
  • 原文地址:https://www.cnblogs.com/wangchaowei/p/9002734.html
Copyright © 2020-2023  润新知