沈静思,韩剧赤道的男人,www19gggcom
本系列文章为《编写高质量代码——改善python程序的91个建议》的精华汇总。
什么是 pythonic?
pythonic的代码就是具有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 发布
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Python 实现将numpy中的nan和inf,nan替换成对应的均值
python爬虫把url链接编码成gbk2312格式过程解析
网友评论