来自Quora的相同问题:Python (programming language): What are the Python features you wish you'd known earlier?
回复内容:
Hidden features of Python
比较符连写:
>>> x = 5 >>> 1 x 10 True >>> 10 > x 9 True测试程序执行的时间import time class Timer: def __enter__(self): self.start = time.clock() return self def __exit__(self,*args): self.end = time.clock() self.interval = self.end-self.start with Timer() as t: dosomesuch() print t.intervalx,y=y,x dir()
还有列表解析式 [i*2 for i in range(100)] 让我们大喊三声:
递归+yield 真好用啊
递归+yield 真好用啊
递归+yield 真好用啊
这绝对是解决一些难题的专用利器.我用它来实现自定义的文件夹遍历函数..对比os.walk函数,我可以在遍历时进行任何操作,灵活许多.
我用它实现了嵌套字典的漂亮 输出,在未理解递归之前,我不敢想象自己能解决这种问题.上例子:def superPrint ( inidic = {}, indent = chr ( 32 )): length = len ( inidic ) for i , d in enumerate ( inidic . items ()): #if the k or v is string object,add ' to both sides k , v = [ "' %s '" % x if isinstance ( x ,( str , unicode )) else x for x in d ] #if the v is dict object,recurse across v and return a string if isinstance ( v , dict ): v = '' . join ( superPrint ( v , indent + chr ( 32 ) * ( len ( str ( k )) + 3 ))) if length == 1 : yield "{ %s : %s }" % ( k , v ) elif i == 0 : yield "{ %s : %s , \n " % ( k , v ) elif i == length - 1 : yield " %s%s : %s }" % ( indent , k , v ) else : yield " %s%s : %s , \n " % ( indent , k , v )比较喜欢map ,reduce,filter省去了很多废话有没有,还有list comprehension。。。
还有高阶函数,闭包。。
另外么,getattr ,hasattr函数吧。。。
with as 结构
in关键字 也很省事。。
其实这些特性别的语言也有,但是第一次见是在python中。。 python 的元组 、序列 、字典 数据结构及其容易操作,切片很实用。
还有Python有很多友好方便的语法糖。help ( something )果断是缩进。。查看更多关于Python的哪些特性或用法让你相见恨晚?的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did89828