# 【译】Python的优雅技巧

### 枚举

``````i = 0
for item in iterable:
print i, item
i += 1
``````

``````for i, item in enumerate(iterable):
print i, item
``````

Enumerate可以接受第二个参数，例如：

``````>>> list(enumerate('abc'))
[(0, 'a'), (1, 'b'), (2, 'c')]

>>> list(enumerate('abc', 1))
[(1, 'a'), (2, 'b'), (3, 'c')]
``````

### 字典/集合 解析

``````my_dict = {i: i * i for i in xrange(100)}
my_set = {i * 15 for i in xrange(100)}
# There is only a difference of ':' in both
``````

### 强制浮点数除法

``````result = 1.0/2
``````

``````from __future__ import division
result = 1/2
# print(result)
# 0.5
``````

### 简单的服务器

``````# Python2
python -m SimpleHTTPServer

# Python 3
python3 -m http.server
``````

### Python表达式求值

``````import ast
my_list = ast.literal_eval(expr)
``````

``````expr = "[1, 2, 3]"
my_list = eval(expr)
``````

### 分析脚本

``````python -m cProfile my_script.py
``````

### 对象自检

``````>>> foo = [1, 2, 3, 4]
>>> dir(foo)
'__delattr__', '__delitem__', '__delslice__', ... ,
'extend', 'index', 'insert', 'pop', 'remove',
'reverse', 'sort']
``````

### 调试脚本

``````import pdb
pdb.set_trace()
``````

### 简化if结构

``````if n in [1,4,5,6]:
``````

``````if n==1 or n==4 or n==5 or n==6:
``````

### 字符串/数列 逆序

``````>>> a = [1,2,3,4]
>>> a[::-1]
[4, 3, 2, 1]

# This creates a new reversed list.
# If you want to reverse a list in place you can do:

a.reverse()
``````

``````>>> foo = "yasoob"
>>> foo[::-1]
'boosay'
``````

### 优雅地打印

``````from pprint import pprint
pprint(my_dict)
``````

``````cat file.json | python -m json.tools
``````

### 三元运算

``````[on_true] if [expression] else [on_false]
x, y = 50, 25
small = x if x < y else y
``````

#### 译文出处：http://www.ido321.com/1576.html

##### 不写代码的码农

Front-end Dev Handbook: 前端开发者手册

12.7k 声望
1.1k 粉丝