Python,由于语言的简单性,让我们可以用人类的思维方式来编写代码。新手更容易上手,老手爱不释手。要编写Pythonic(优雅、真实、干净)代码,您还需要观察那些伟大的代码。Github上有很多优秀的源码值得一读,比如:requests、flask、tornado,这里是我的参考,除了自己在其他文章中的经验外,收集了一些常用的Pythonic写法,希望对大家的开发有所帮助编写优秀代码的习惯。01.变量交换Badtmp=aa=bb=tmpPython,b=b,a02。列表理解Badmy_list=[]foriinrange(10):my_list.append(i*2)Pythonicmy_list=[i*2foriinrange(10)]03。单行表达式尽管列表理解因其简单性和表现力而广受赞誉。但是有很多表达式可以写在一行中,这不是很好的做法。坏字“一”;print'two'ifx==1:print'one'if和:#dosomethingPythonicprint'one'print'two'ifx==1:print'one'cond1=cond2=ifcond1andcond2:#dosomething04.带索引遍历Badforiinrange(len(my_list)):print(i,"-->",my_list[i])Pythonicfori,iteminenumerate(my_list):print(i,"-->",item)05。顺序解析Python,*rest=[1,2,3]#a=1,rest=[2,3]a,*middle,c=[1,2,3,4]#a=1,middle=[2,3],c=406.字符串拼接Badletters=['s','p','a','m']s=""forletinletters:s+=letPythonicletters=['s','p','a','m']word=''.join(letters)07.真假判断Badifattr==True:print'True!'ifattr==None:print'attrisNone!'Pythonicifattr:print'attristruthy!'ifnotattr:print'attrisfalsey!'ifattr是无:打印'attr是无!'08。访问字符串元素Badd={'hello':'world'}ifd.has_key('hello'):printd['hello']#打印'world'else:print'default_value'Pythonicd={'hello':'world'}printd.get('hello','default_value')#打印'world'printd.get('thingy','default_value')#打印'default_value'#或者:如果d中有'hello':printd['hello']09。操作列表Bada=[3,4,5]b=[]foriina:ifi>4:b.append(i)Pythonica=[3,4,5]b=[iforiinaifi>4]#Or:b=filter(lambdax:x>4,a)Bada=[3,4,5]foriinrange(len(a)):a[i]+=3Pythonica=[3,4,5]a=[i+3foriina]#或者:a=map(lambdai:i+3,a)10.文件读取取Badf=open('file.txt')a=f.read()printaf.close()Pythonicwithopen('file.txt')asf:forlineinf:printline11.代码连续行Badmy_very_big_string="""很长一段时间我习惯早睡。有时,\当我熄灭蜡烛时,我的眼睛会很快闭上,以至于我什至\没有时间说“我是去睡觉了。”“”“从some.deep.module.inside.a.module导入a_nice_function,another_nice_function,\yet_another_nice_functionPythonicmy_very_big_string=("很长一段时间我习惯早睡。有时,""当我熄灭蜡烛时,我的眼睛会很快闭上""以至于我什至没有时间说“我'mgoingtosleep."")fromsome.deep.module.inside.a.moduleimport(a_nice_function,another_nice_function,yet_another_nice_function)12.显式代码Baddefmake_complex(*args):x,y=argsreturndict(**locals())Pythonicdefmake_complex(x,y):return{'x':x,'y':y}13.使用占位符Pythonicfilename='foobar.txt'basename,_,ext=filename.rpartition('.')14.链式比较Badifage>18andage<60:print("youngman")Pythonif18>>False==False==TrueFalse15.三目操作的保留和使用习惯一样好。Badifa>2:b=2else:b=1#b=2Pythonica=3b=2ifa>2else1#b=2参考文档http://docs.python-guide.org/...https://foofish.net/惯用语…