参考,搬运

  1. http://python-web-guide.readthedocs.io/zh/latest/idiom/idiom.html
  2. 待定

1. Python支持链式比较

# bad
a = 5
if a > 1 and a < 7:
pass
# good
if 1 < a < 7:
pass

2. Python交换变量

# bad
x = 10
y = 5
tmp = x
x = y
y = tmp # good
x = 10
y = 5
x, y = y, x

3. Python中替代三目运算符?:

# bad
a = 10
b = 5
if a > b:
c = a
else:
c = b
# good
c = a if a > b else b

4. 格式化字符时多使用format函数

# bad
name = "tony"
age = 100
str = "myname : " + name + " my age : " + str(age)
str1 = "myname : %s my age : %d" % (name, age)
# good
str2 = "myname : {} my age {}".format(name, age)

5. 使用列表或者字典comprehension(推导式)

# bad
mylist = range(20)
odd_list = []
for e in mylist:
if e % 2 == 1:
odd_list.append(e)
# good
odd_list = [e for e in mylist if e % 2 == 1] # bad
user_list = [{'name': 'lucy', 'email': 'lucy@g.com'}, {'name': 'lily', 'email': 'lily@g.com'}]
user_email = {}
for user in user_list:
if 'email' in user:
user_email[user['name']] = user['email']
# good
{user['name']: user['email'] for user in user_list if 'email' in user}

6. 条件判断时,避免直接和True, False, None进行比较(==)

# bad
if l == []:
pass
# good
if l: # 实际调用l.__len__() == 0
pass # bad
if something == None:
# good, None 是单例对象
if something is None:

7. 使用enumerate代替for循环中的index变量访问

# bad
my_container = ['lily', 'lucy', 'tom']
index = 0
for element in my_container:
print '{} {}'.format(index, element)
index += 1 # good
for index, element in enumerate(my_container):
print '%d %s' % (index, element)

8. 避免使用可变(mutable)变量作为函数参数的默认初始化值

# bad
def function(l = []):
l.append(1)
return l print function()
print function()
print function() # print
[1]
[1, 1]
[1, 1, 1] # good 使用None作为可变对象占位符
def function(l=None):
if l is None:
l = []
l.append(1)
return l

9. 一切皆对象

# bad
def print_addition_table():
for x in range(1, 3):
for y in range(1, 3):
print(str(x + y) + '\n') def print_subtraction_table():
for x in range(1, 3):
for y in range(1, 3):
print(str(x - y) + '\n') def print_multiplication_table():
for x in range(1, 3):
for y in range(1, 3):
print(str(x * y) + '\n') def print_division_table():
for x in range(1, 3):
for y in range(1, 3):
print(str(x / y) + '\n') print_addition_table()
print_subtraction_table()
print_multiplication_table()
print_division_table() # good, python一切都是对象,可以函数作为参数,类似技巧可以用来简化代码
import operator as op def print_table(operator):
for x in range(1, 3):
for y in range(1, 3):
print(str(operator(x, y)) + '\n') for operator in (op.add, op.sub, op.mul, op.div):
print_table(operator)

10. 防御式编程EAFP vs LBYL

# LBYL
def getPersonInfo(person):
if person == None:
print 'person must be not null!'
print person.info # EAFP
def getPersonInfo(person):
try:
print person.info
except NameError:
print 'person must be not null!'

11. 用dict对象完成switch...case...的功能

# bad
def apply_operation(left_operand, right_operand, operator):
if operator == '+':
return left_operand + right_operand
elif operator == '-':
return left_operand - right_operand
elif operator == '*':
return left_operand * right_operand
elif operator == '/':
return left_operand / right_operand
# good
def apply_operation(left_operand, right_operand, operator):
import operator as op
operator_mapper = {'+': op.add, '-': op.sub, '*': op.mul, '/': op.truediv}
return operator_mapper[operator](left_operand, right_operand)

12. 访问tuple的数据项时,可以用namedtuple代替index的方式访问

# bad
rows = [('lily', 20, 2000), ('lucy', 19, 2500)]
for row in rows:
print '{}`age is {}, salary is {} '.format(row[0], row[1], row[2]) # good
from collections import namedtuple
Employee = namedtuple('Employee', 'name, age, salary')
for row in rows:
employee = Employee._make(row)
print '{}`age is {}, salary is {} '.format(employee.name, employee.age, employee.salary)

13. 用isinstance来判断对象的类型

下面的代码是计算一个对象的长度值,如果是序列类型(str,list,set,dict)的, 直接调用len方法,如果是True, False, None则返回1,如果是数值的,则返回其int值.

# bad
def get_size(some_object):
try:
return len(some_object)
except TypeError:
if some_object in (True, False, None):
return 1
else:
return int(some_object) print(get_size('hello'))
print(get_size([1, 2, 3, 4, 5]))
print(get_size(10.0)) # good
def get_size(some_object):
if isinstance(some_object, (list, dict, str, tuple)):
return len(some_object)
elif isinstance(some_object, (bool, type(None))):
return 1
elif isinstance(some_object, (int, float)):
return int(some_object)

14. 用with管理操作资源的上下文环境

上下文协议需要实现__enter__和__exit__方法

# bad
class Connection(object):
def execute(self, sql):
raise Exception('ohoh, exception!') def close(self):
print 'closed the Connection' try:
conn = Connection()
conn.execute('select * from t_users')
finally:
conn.close() # good
class Connection(object):
def execute(self, sql):
raise Exception('ohoh, exception!') def close(self):
print 'closed the Connection' def __enter__(self):
return self def __exit__(self, errorType, errorValue, error):
self.close() with Connection() as conn:
conn.execute('select * from t_users')

15. 使用generator返回耗费内存的对象

# bad
def f():
# ...
return biglist # bad
def f():
# ...
return biglist # good
def f():
# ...
for i in biglist:
yield i

Python - 编程技巧,语法糖,黑魔法,pythonic的更多相关文章

  1. python编程技巧2

    模块化 ---- 这是我们程序员梦寐以求的,通过模块化可以避免重复的制造轮子. 同时 模块让你能够有逻辑地组织你的Python代码段. 把相关的代码分配到一个 模块里能让你的代码更好用,更易懂. 模块 ...

  2. python的一些语法糖

    1   Python中if-else语句的多种写法 a, b, c = 1, 2, 3 1.常规 if a>b: c = a else: c = b 2.表达式 c = a if a>b  ...

  3. 一十九条优雅Python编程技巧

    1.交换赋值 #不推荐 temp = a a = b b = a #推荐 a , b = b , a #先生成一个元组(tuple)对象,然后在unpack 2.Unpacking #不推荐 l = ...

  4. Python 编程技巧

    Python 生成器 Python 处理文件 Python 异常处理 Python 处理输入输出 Python 处理命令行参数 Python 对文件做校验 Python 对目录做遍历 Python 调 ...

  5. python装饰器 语法糖

    简介: 装饰器(Decorators)是 Python 的一个重要部分.简单地说:他们是修改其他函数的功能的函数. 比如说我们写flask,路由就是用装饰器定义的.如果写权限控制,那么权限控制一般也是 ...

  6. python 装饰器(语法糖)

    def  login(func):    def testlogin():        for  i in range(3):            _username="abc" ...

  7. python编程技巧

  8. 【Python】从1<2<3的语法糖说起

    python有一个很有意思的语法糖你可以直接写1<2<3. 这复合我们通常意义上的数学不等式,但对学过C等语言其实是有疑惑的. 我们知道不等式返回的其实是个Bool值,在C中是1,0因此C ...

  9. 学习 Python 编程的 19 个资源 (转)

    学习 Python 编程的 19 个资源 2018-01-07 数据与算法之美 编译:wzhvictor,英文:codecondo segmentfault.com/a/119000000418731 ...

随机推荐

  1. SpringMVC--使用hibernate validator数据校验

    JSR 303 Spring3开始支持JSR 303 验证框架,JSR303是Java为Bean数据合法性校验所提供的标准框架.JSR 303 支持XML和注解风格的验证,通过在Bean属性上标注类似 ...

  2. 【游戏体验】Colour My World(让我的世界充满色彩)

    这是一款玩法简单的游戏 但是它给你的感觉不一样 推荐试玩 个人测评 游戏性 7/10 音乐 9/10 剧情 6/10 总评 22/30

  3. 委托与事件--delegate&&event

    委托 访问修饰符 delegate 返回值 委托名(参数); public delegate void NoReturnNoPara(); public void NoReturnNoParaMeth ...

  4. jquer_shijian 增加初始化 年月日 及 结束时间 年月日

    增加了插件 在初始化的时候,控制 年月日,和结束 年月日 $(time_createobj).siblings(".xtw_budget_userdatafn_hide").shi ...

  5. List 线性表:ArrayLis,LinkedList

    package seday11.list; import java.util.ArrayList;import java.util.List; /*** @author xingsir * java. ...

  6. 深度学习之反向传播算法(BP)代码实现

    反向传播算法实战 本文仅仅是反向传播算法的实现,不涉及公式推导,如果对反向传播算法公式推导不熟悉,强烈建议查看另一篇文章神经网络之反向传播算法(BP)公式推导(超详细) 我们将实现一个 4 层的全连接 ...

  7. django模块导入/函数/中间件/MVC和MTV/CSRF

    目录 一:模块导入 二:函数 三:中间件 四:MVC和MTV 五:csrf 一:模块导入 第一种:继承 这里的母版更像是一个架子,子板都是定义的内容(如果多个页面中 ,存在相同的页面:这样我们可以抽到 ...

  8. 原生js按回车键实现登录

    这篇文章主要介绍了原生JS按回车键实现登录的方法,众所周知,这是在web程序设计中的一个非常实用的小技巧,主要用于表单提交,包括注册.登录等等功能,具有很好的用户体验,有着非常广泛的实用价值,需要的朋 ...

  9. Jmeter_JsonPath 提取器

    1.登录老黄历 2.提取阳历的数据,不用正则表达式提取器,因为这里是字典形式,用Json path提取器更简单 3.把提取的数据放到百度里去发送请求 4. 5. 6. 7. 8. 9.

  10. 【C语言】输入一个正整数,判断其是否为素数

    素数的定义: 素数(prime number)又称质数,有无限个. 素数定义为在大于1的自然数中,除了1和它本身以外不再有其他因数,这样的数称为素数.代码1: #include<stdio.h& ...