15个Pythonic的代码示例(值得收藏)
Python由于语言的简洁性,让我们以人类思考的方式来写代码,新手更容易上手,老鸟更爱不释手。
要写出Pythonic(优雅的、地道的、整洁的)代码,还要平时多观察那些大牛代码,Github上有很多非常优秀的源代码值得阅读,比如:requests、flask、tornado,这里小明收集了一些常见的Pythonic写法,帮助你养成写优秀代码的习惯。
01.变量交换
Bad
tmp=a a=b b=tmp
Pythonic
a,b=b,a
02.列表推导
Bad
my_list=[] foriinrange(10): my_list.append(i*2)
Pythonic
my_list=[i*2foriinrange(10)]
03.单行表达式
虽然列表推导式由于其简洁性及表达性,被广受推崇。
但是有许多可以写成单行的表达式,并不是好的做法。
Bad
print'one';print'two' ifx==1:print'one' ifand : #dosomething
Pythonic
print'one' print'two' ifx==1: print'one' cond1=cond2= ifcond1andcond2: #dosomething
04.带索引遍历
Bad
foriinrange(len(my_list)): print(i,"-->",my_list[i])
Pythonic
fori,iteminenumerate(my_list): print(i,"-->",item)
05.序列解包
Pythonic
a,*rest=[1,2,3] #a=1,rest=[2,3] a,*middle,c=[1,2,3,4] #a=1,middle=[2,3],c=4
06.字符串拼接
Bad
letters=['s','p','a','m'] s="" forletinletters: s+=let
Pythonic
letters=['s','p','a','m'] word=''.join(letters)
07.真假判断
Bad
ifattr==True: print'True!' ifattr==None: print'attrisNone!'
Pythonic
ifattr: print'attristruthy!' ifnotattr: print'attrisfalsey!' ifattrisNone: print'attrisNone!'
08.访问字典元素
Bad
d={'hello':'world'} ifd.has_key('hello'): printd['hello']#prints'world' else: print'default_value'
Pythonic
d={'hello':'world'} printd.get('hello','default_value')#prints'world' printd.get('thingy','default_value')#prints'default_value' #Or: if'hello'ind: printd['hello']
09.操作列表
Bad
a=[3,4,5] b=[] foriina: ifi>4: b.append(i)
Pythonic
a=[3,4,5] b=[iforiinaifi>4] #Or: b=filter(lambdax:x>4,a)
Bad
a=[3,4,5] foriinrange(len(a)): a[i]+=3
Pythonic
a=[3,4,5] a=[i+3foriina] #Or: a=map(lambdai:i+3,a)
10.文件读取
Bad
f=open('file.txt') a=f.read() printa f.close()
Pythonic
withopen('file.txt')asf: forlineinf: printline
11.代码续行
Bad
my_very_big_string="""ForalongtimeIusedtogotobedearly.Sometimes,\ whenIhadputoutmycandle,myeyeswouldclosesoquicklythatIhadnoteven\ timetosay“I'mgoingtosleep.”""" fromsome.deep.module.inside.a.moduleimporta_nice_function,another_nice_function,\ yet_another_nice_function
Pythonic
my_very_big_string=( "ForalongtimeIusedtogotobedearly.Sometimes," "whenIhadputoutmycandle,myeyeswouldclosesoquickly" "thatIhadnoteventimetosay“I'mgoingtosleep.”" ) fromsome.deep.module.inside.a.moduleimport( a_nice_function,another_nice_function,yet_another_nice_function)
12.显式代码
Bad
defmake_complex(*args): x,y=args returndict(**locals())
Pythonic
defmake_complex(x,y): return{'x':x,'y':y}
13.使用占位符
Pythonic
filename='foobar.txt' basename,_,ext=filename.rpartition('.')
14.链式比较
Bad
ifage>18andage<60: print("youngman")
Pythonic
if18理解了链式比较操作,那么你应该知道为什么下面这行代码输出的结果是False
>>>False==False==True False15.三目运算
这个保留意见。随使用习惯就好。
Bad
ifa>2: b=2 else: b=1 #b=2Pythonic
a=3 b=2ifa>2else1 #b=2参考文档
http://docs.python-guide.org/en/latest/writing/style/
https://foofish.net/idiomatic_part2.html
到此这篇关于15个Pythonic的代码示例(值得收藏)的文章就介绍到这了,更多相关Pythonic代码内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!