30 个有关 Python 的小技巧
转载自 30 Python Language Features and Tricks You May Not Know About
中文版 30个有关Python的小技巧
批量赋值
Unpacking
1, 2, 3 a, b, c = |
Unpacking for swapping variables
1, 2 a, b = |
Extended unpacking (Python 3 only)
1, 2, 3, 4, 5] a, *b, c = [ |
list & dictionary / 列表和字典
Negative indexing
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] a = [ |
List slices (a[start:end])
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] a = [ |
List slices with negative indexing
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] a = [ |
List slices with step (a[start:end:step])
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] a = [ |
List slices with negative step
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] a = [ |
List slice assignment / 切割并赋值
1, 2, 3, 4, 5] a = [ |
for循环取list的索引和值 (enumerate)
'Hello', 'world', '!'] a = [ |
list加入索引值 (enumerate)
'Spring', 'Summer', 'Fall', 'Winter'] seasons = [ |
Naming slices (slice(start, end, step)) / 给切割操作命名
0, 1, 2, 3, 4, 5] a = [ |
Zipping and unzipping lists and iterables / 列表以及迭代器的压缩和解压缩
1, 2, 3] a = [ |
Grouping adjacent list items using zip / 列表相邻元素压缩器
1, 2, 3, 4, 5, 6] a = [ |
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)
'a': 1, 'b': 2, 'c': 3, 'd': 4} m = { |
Inverting a dictionary / 字典与表的转换, 以及翻转
# using zip |
Dictionary comprehensions / 快速生成规律性字典
2 for x in range(5)} m = {x: x ** |
语法上的一些技巧
双重for循环
'la','luo','lao') a = ( |
python 中 switch 的替代方案
# 字典映射 |
python 仅允许单实例
class Singleton(object): |
Generator expressions / 生成器表达式
2 for x in xrange(10)) g = (x ** |
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 / 集合及其操作
1, 2, 3, 3} A = { |
统计列表中元素出现的次数
2,2,2,2,2,2,3,3,3,3] mylist = [ |
Multisets and multiset operations (collections.Counter) / 多重集合(显示元素个数)
1, 2, 2]) A = collections.Counter([ |
Most common elements in an iterable (collections.Counter) / 统计在可迭代器中最常出现的元素
1, 1, 2, 2, 3, 3, 3, 3, 4, 5, 6, 7]) A = collections.Counter([ |
Double-ended queue (collections.deque) / 双向队列, 近似于双向链表
Q = collections.deque() |
Double-ended queue with maximum length (collections.deque) / 限长的双向队列
3) last_three = collections.deque(maxlen= |
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) / 最大和最小的几个列表元素
0, 100) for __ in xrange(100)] a = [random.randint( |
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) / 可链接迭代器
1, 2, 3, 4] a = [ |
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的小技巧