1. 易混淆操作
在Python编程中,有些操作容易混淆,让我们来对它们进行对比。
1.1 有放回随机采样和无放回随机采样
<code>import random random.choices(seq, k=1) # 有放回采样 random.sample(seq, k) # 无放回采样</code>
1.2 lambda 函数的参数
<code>func = lambda y: x + y # x在函数运行时绑定 func = lambda y, x=x: x + y # x在函数定义时绑定</code>
1.3 copy 和 deepcopy
<code>import copy y = copy.copy(x) # 浅复制 y = copy.deepcopy(x) # 深复制</code>
1.4 == 和 is
<code>x == y # 值相等 x is y # 同一对象</code>
1.5 判断类型
<code>type(a) == int # 忽略多态 isinstance(a, int) # 考虑多态</code>
1.6 字符串搜索
<code>str.find(sub, start=None, end=None); str.rfind(...) # 找不到返回-1 str.index(sub, start=None, end=None); str.rindex(...) # 找不到抛出异常</code>
1.7 List 后向索引
<code>print(a[-1], a[-2], a[-3]) print(a[~0], a[~1], a[~2]) # 使用~从0开始反向索引</code>
2. 常用工具
2.1 读写 CSV 文件
<code>import csv # 无header的读写 with open(name, 'rt', encoding='utf-8', newline='') as f: for row in csv.reader(f): print(row[0], row[1]) with open(name, mode='wt') as f: f_csv = csv.writer(f) f_csv.writerow(['symbol', 'change']) # 有header的读写 with open(name, mode='rt', newline='') as f: for row in csv.DictReader(f): print(row['symbol'], row['change']) with open(name, mode='wt') as f: header = ['symbol', 'change'] f_csv = csv.DictWriter(f, header) f_csv.writeheader() f_csv.writerow({'symbol': xx, 'change': xx})</code>
2.2 迭代器工具
<code>import itertools itertools.islice(iterable, start=None, stop, step=None) itertools.filterfalse(predicate, iterable) itertools.takewhile(predicate, iterable) itertools.dropwhile(predicate, iterable) itertools.compress(iterable, selectors) itertools.chain(*iterables)</code>
2.3 计数器
<code>import collections collections.Counter(iterable)</code>
2.4 带默认值的 Dict
<code>import collections collections.defaultdict(type)</code>
2.5 有序 Dict
<code>import collections collections.OrderedDict(items=None)</code>
3. 高性能编程和调试
3.1 输出错误和警告信息
<code>import sys sys.stderr.write('') import warnings warnings.warn(message, category=UserWarning)</code>
3.2 代码中测试
<code>if __debug__: pass</code>
3.3 代码风格检查
<code>pylint main.py</code>
3.4 代码耗时
<code>$ python -m cProfile main.py</code>
4. Python 其他技巧
4.1 argmin 和 argmax
<code>items = [2, 1, 3, 4] argmin = min(range(len(items)), key=items.__getitem__)</code>
4.2 转置二维列表
<code>A = [['a11', 'a12'], ['a21', 'a22'], ['a31', 'a32']] A_transpose = list(zip(*A)) # list of tuple</code>
4.3 一维列表展开为二维列表
<code>A = [1, 2, 3, 4, 5, 6] list(zip(*[iter(A)] * 2))</code>
这些技巧将帮助您在Python编程中更加得心应手,提高效率,增加代码的可读性和可维护性。
© 版权声明
THE END
暂无评论内容