Python - 编程技巧,语法糖,黑魔法,pythonic
参考,搬运
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的更多相关文章
- python编程技巧2
模块化 ---- 这是我们程序员梦寐以求的,通过模块化可以避免重复的制造轮子. 同时 模块让你能够有逻辑地组织你的Python代码段. 把相关的代码分配到一个 模块里能让你的代码更好用,更易懂. 模块 ...
- 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 ...
- 一十九条优雅Python编程技巧
1.交换赋值 #不推荐 temp = a a = b b = a #推荐 a , b = b , a #先生成一个元组(tuple)对象,然后在unpack 2.Unpacking #不推荐 l = ...
- Python 编程技巧
Python 生成器 Python 处理文件 Python 异常处理 Python 处理输入输出 Python 处理命令行参数 Python 对文件做校验 Python 对目录做遍历 Python 调 ...
- python装饰器 语法糖
简介: 装饰器(Decorators)是 Python 的一个重要部分.简单地说:他们是修改其他函数的功能的函数. 比如说我们写flask,路由就是用装饰器定义的.如果写权限控制,那么权限控制一般也是 ...
- python 装饰器(语法糖)
def login(func): def testlogin(): for i in range(3): _username="abc" ...
- python编程技巧
- 【Python】从1<2<3的语法糖说起
python有一个很有意思的语法糖你可以直接写1<2<3. 这复合我们通常意义上的数学不等式,但对学过C等语言其实是有疑惑的. 我们知道不等式返回的其实是个Bool值,在C中是1,0因此C ...
- 学习 Python 编程的 19 个资源 (转)
学习 Python 编程的 19 个资源 2018-01-07 数据与算法之美 编译:wzhvictor,英文:codecondo segmentfault.com/a/119000000418731 ...
随机推荐
- cef源码分析之cefsimple
下面是cefsimple的入口代码,主要分成两个部分 // Entry point function for all processes. int APIENTRY wWinMain(HINSTANC ...
- VS2015打开失败
在使用VS2015过程中之前能打开的.Net项目,结果突然就不能使用了.我就不能理解了,后来找了一个方法,抱着试试的心态结果就成功了. 解决办法 第一步: 开始-->所有程序-->Micr ...
- stl队列
队列(Queue)也是一种运算受限的线性表,它的运算限制与栈不同,是两头都有限制,插入只能在表的一端进行(只进不出),而删除只能在表的另一端进行(只出不进),允许删除的一端称为队尾(rear),允许插 ...
- Angular 2.0 文本拖拽
基于Angular7.1和TypeScript实现 Html代码 <div style="padding-left: 0px;"> <div id='conten ...
- Docker - 容器的 连接 与 退出
概述 连接容器, 退出容器 命令 run exec attach 退出 选项 -i -t -d 1. docker run 概述 docker run 通常用来创建新容器 docker run 的 三 ...
- 使用docker容器时遇到的2个问题
最近项目在centOS7服务器上用docker部署了几个服务,在运行的时候发现,总是过一段时间,容器内的根目录就变为只读而无法写入了. 经过调查都是因为docker/devicemapper/devi ...
- 基于jmeter+ant实现的接口自动化测试
jmeter+ANT接口自动化测试框架 项目说明 本框架是一套基于jmeter+Ant+Excel+Python而设计的数据驱动接口自动化测试框架,jmeter 作为执行器,Ant 作为构建工具,进行 ...
- tarjan-无向图(求割点)
一.基本概念 1.割点:无向连通图中,如果删除某点后,图变成不连通,则称改点为割点. 2.桥:无向连通图中,如果去掉某条边后,整张无向图会分成两部分(即整张图不连通),这样的一条边成为桥. 3.点双连 ...
- python-turtle-画雪花-2种方法及效果的详解
1.方法一: 代码: #python3.8 #xuguojun #2020.1.30 #导出模块 import turtle as t import random as r #定义画雪 def dra ...
- 【PAT甲级】1089 Insert or Merge (25 分)(插入排序和归并排序)
题意: 输入一个正整数N(<=100),接着输入两行N个整数,第一行表示初始序列,第二行表示经过一定程度的排序后的序列.输出这个序列是由插入排序或者归并排序得到的,并且下一行输出经过再一次排序操 ...