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 ...
随机推荐
- AcWing 869. 试除法求约数
#include <iostream> #include <algorithm> #include <vector> using namespace std; ve ...
- 题解【POJ1651】Multiplication Puzzle
Description The multiplication puzzle is played with a row of cards, each containing a single positi ...
- C语言当中int,float,double,char这四个有什么区别?
区别在以下方面: 一.定义方面: 1.int为整数型,用于定义整数类型的数据 . 2.float为单精度浮点型,能准确到小数点后六位 . 3.double为双精度浮点型,能准确到小数点都十二位 . 4 ...
- CSS学习(10)行盒盒模型
常见的行盒:包含具体内容的元素 span.strong.em.i.img.video.audio 显著特点: 1.盒子沿着内容延伸 2.行盒不能设置宽高,调整行盒的宽高,应使用字体大小.行高.字体类型 ...
- Java 前加加和后加加 总结
public class Test { public static void main(String[] args) { int age = 6; //先自加,再使用(age先自加1,然后再打印age ...
- docker删除mysql镜像失败Error response from daemon: conflict: unable to delete 8809d5286227 (must be forced) - image is being used by stopped container 1a2a427273b3
错误解析:这是由于要删除的目标镜像中有容器存在,故无法删除镜像 解决办法:先删除镜像中的容器,再删除该镜像.
- 在IDEA离线安装lombok插件
1.打开,找到自己IDEA版本,idea http://plugins.jetbrains.com/plugin/6317-lombok/versions 2.下载,导入安装
- 前端框架vue学习笔记:环境搭建
兼容性 不兼容IE8以下 Vue Devtools 能够更好的对界面进行审查和调试 环境搭建 1.nodejs(新版本的集成了npm)[npm是node包管理 node package manager ...
- rsyslog日志服务部署
rsyslog简介 rsyslog是CentOS6和CentOS7默认的记录日志的服务 支持特性: UDP, TCP, SSL, TLS, RELP MySQL, PGSQL, Oracle实现日志存 ...
- 初探three.js几何体-Geometry
three.js几何体我们还没有说完,这一节我们说一说THREE.Geometry(),简单几何体都是继承了这个对象,使用它会相对麻烦一些,但是可操作性非常高,今天我们使用它制作一个自定义几何体-五角 ...