Python 中的那些坑总结——持续更新
2024-08-24 14:25:57
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()
最新文章
- Effective C++ 34 区分接口继承和实现继承
- 微信支付报错:Invalid thumbnail dimensions: 0x0
- 小JAVA大世界之程序建模跳蚤实验
- javascript基础程序(算出一个数的平方值、算出一个数的阶乘、输出!- !- !- !- !- -! -! -! -! -! 、函数三个数中的最大数)
- C#中的线程一(委托中的异步)
- C#如何在钉钉开发平台中创建部门
- 利用PowerDesigner比较2个数据库结构
- nginx搭建流媒体服务器的方法详解
- python参考手册--第4、5、6、7章
- C++的4种编程范型
- 第七章Bulk设备
- Qt中文乱码问题(比较清楚,同一个二进制串被解释成不同的语言)
- 一步一步学android之事件篇——触摸事件
- Ubuntu 13.10 安装 Unity 8 试用截图
- css3标签学习总结文章
- 【转】JDBC学习笔记(1)——JDBC概述
- angular4升级angular5问题记录之No NgModule metadata found for &#39;AppModule&#39;
- 一次完整的HTTP网络请求过程详解
- 对于rqy今天讲座的一些理解和看法吧
- 注册InstallShield
热门文章
- 170703、springboot编程之模板使用(thymeleaf、freemarker)
- 遍历DataSet
- HDU 1403 Eight&POJ 1077(康拖,A* ,BFS,双广)
- Django - rest - framework - 下
- inotify+rsync安装配置
- 一个用于提取简体中文字符串中省,市和区并能够进行映射,检验和简单绘图的python模块
- django自带权限机制
- [RGEOS]空间拓扑关系
- WebDriver API 实例详解(一)
- PAT 1129 Recommendation System[比较]