30 个有关 Python 的小技巧
转载自 30 Python Language Features and Tricks You May Not Know About
中文版 30个有关Python的小技巧
批量赋值
Unpacking
a, b, c = 1, 2, 3 |
Unpacking for swapping variables
a, b = 1, 2 |
Extended unpacking (Python 3 only)
a, *b, c = [1, 2, 3, 4, 5] |
list & dictionary / 列表和字典
Negative indexing
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
List slices (a[start:end])
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
List slices with negative indexing
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
List slices with step (a[start:end:step])
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
List slices with negative step
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
List slice assignment / 切割并赋值
a = [1, 2, 3, 4, 5] |
for循环取list的索引和值 (enumerate)
a = ['Hello', 'world', '!'] |
list加入索引值 (enumerate)
seasons = ['Spring', 'Summer', 'Fall', 'Winter'] |
Naming slices (slice(start, end, step)) / 给切割操作命名
a = [0, 1, 2, 3, 4, 5] |
Zipping and unzipping lists and iterables / 列表以及迭代器的压缩和解压缩
a = [1, 2, 3] |
Grouping adjacent list items using zip / 列表相邻元素压缩器
a = [1, 2, 3, 4, 5, 6] |
Sliding windows (n-grams) using zip and iterators / 列表元素压缩器(同上方法二)
from itertools import islice |
Flattening lists: / 列表展开
Note: according to Python’s documentation on sum, itertools.chain.from_iterable is the preferred method for this.
# 推荐使用 itertools.chain.from_iterable |
for循环取dict的关键字和值 (iteritems)
m = {'a': 1, 'b': 2, 'c': 3, 'd': 4} |
Inverting a dictionary / 字典与表的转换, 以及翻转
# using zip |
Dictionary comprehensions / 快速生成规律性字典
m = {x: x ** 2 for x in range(5)} |
语法上的一些技巧
双重for循环
a = ('la','luo','lao') |
python 中 switch 的替代方案
# 字典映射 |
python 仅允许单实例
class Singleton(object): |
Generator expressions / 生成器表达式
g = (x ** 2 for x in xrange(10)) |
Learn the Zen of Python / 打印Python之道
import this |
使用C语言括号替代缩进
from __future__ import braces |
collections 的一些数据类型
Named tuples (collections.namedtuple) / 类似于 C 的struct结构
import collections |
Inheriting from named tuples: / 自定义 namedtuple 的运算
class Point(collections.namedtuple('PointBase', ['x', 'y'])): |
Sets and set operations / 集合及其操作
A = {1, 2, 3, 3} |
统计列表中元素出现的次数
mylist = [2,2,2,2,2,2,3,3,3,3] |
Multisets and multiset operations (collections.Counter) / 多重集合(显示元素个数)
A = collections.Counter([1, 2, 2]) |
Most common elements in an iterable (collections.Counter) / 统计在可迭代器中最常出现的元素
A = collections.Counter([1, 1, 2, 2, 3, 3, 3, 3, 4, 5, 6, 7]) |
Double-ended queue (collections.deque) / 双向队列, 近似于双向链表
Q = collections.deque() |
Double-ended queue with maximum length (collections.deque) / 限长的双向队列
last_three = collections.deque(maxlen=3) |
Ordered dictionaries (collections.OrderedDict) / 可排序字典
# 普通字典 |
Default dictionaries (collections.defaultdict) / 默认字典
# 普通字典 |
Using default dictionaries to represent simple trees / 默认字典实现树, 快速生成xml文件
See One-line Tree in Python for more on this.
import json |
Mapping objects to unique counting numbers (collections.defaultdict) / 生成对象的唯一索引值
import itertools, collections |
Largest and smallest elements (heapq.nlargest and heapq.nsmallest) / 最大和最小的几个列表元素
a = [random.randint(0, 100) for __ in xrange(100)] |
itertools 迭代器的一些应用
Cartesian products (itertools.product) / 两个列表的笛卡尔积
for p in itertools.product([1, 2, 3], [4, 5]): |
Combinations and combinations with replacement (itertools.combinations and itertools.combinations_with_replacement) / 列表组合和列表元素替代组合
for c in itertools.combinations([1, 2, 3, 4, 5], 3): |
Permutations (itertools.permutations) / 列表元素排列组合
for p in itertools.permutations([1, 2, 3, 4]): |
Chaining iterables (itertools.chain) / 可链接迭代器
a = [1, 2, 3, 4] |
Grouping rows by a given key (itertools.groupby) / 根据文件指定列类聚
from operator import itemgetter |
转载自 30 Python Language Features and Tricks You May Not Know About
中文版 30个有关Python的小技巧