本系列文章为《编写高质量代码——改善Python程序的91个建议》的精华汇总。
Pythonic的代码就是具备Python独特风格的代码。通俗说来,就是在保证代码可读性的前提下,尽量地简洁、优雅,看起来像伪代码同样。python
具备 Python 代码风格的例子算法
str.format()
格式化字符串,是最Pythonic的字符串格式化方法。# 交换两个变量 a, b = b, a # for循环遍历容器 for elem in alist: do_sth_with(elem) # format格式化字符串 print("{greet} from {language}!".format(greet="hello, world!", language="Python"))
注意要避免的事:框架
深刻理解Pythonic的几个途径:函数
{}
分隔代码块,Python中用缩进分隔,避免混用空格和Tab键。'
与"
: 在C语言中,单引号'
表示单个的字符型数据(char),双引号"
表示字符串,默认以\0
结尾;在Python中,'
和"
无明显区别。?:
: C语言中的三元操做符 C?X:Y
,表示当条件C为True的时候,取值X,不然取值Y。在Python中的等价形式为 X if C else Y
。switch...case
分支语句,Python中可使用if...elif...else...
代替。Python中有3种形式注释:工具
须要注意:布局
x = x + 1 # 这样的注释略近 x = x + 1 # 更好的注释位置
def get_lines(name, lines): """Return lines that begin with name. Lines are expected to look like: name: space separated values Args: name: string, parameter name. lines: iterable of string, lines in the file. Returns: List of values in the lines that match. """ retval = [] matches = itertools.ifilter(lambda x: x.startswith(name + ":"), lines) for line in matches: retval.extend(line[len(name) + 1 :].split()) return retval
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not ...
def A(): B() def B(): pass
空格的使用学习
=
,比较(==, <, >, !=, <=, >=, in, not in, is, is not
),布尔运算(and, or, not
))的左右两边。如x == 1
[]
之间不须要空格,函数的参数=
两侧不须要空格。本文由博客群发一文多发等运营工具平台 OpenWrite 发布