你可能所不知道的python中有用的特性

来自stackoverflow中python标签下按投票数排列第一位的问题:Hidden features of Python 

题记:我们没有黑魔法,我们是可读的。 
Python is a dynamically and strongly typed programming language that encourages readability. 

1.链式操作符,要注意执行顺序问题,方法是加括号。 
Python代码   收藏代码
  1. >>> x = 5  
  2. >>> 10 < x < 20   
  3. False  
  4. >>> x < 10 < x*10 < 100  
  5. True  

2.debug regex 
Python代码   收藏代码
  1. >>> re.compile(""" 
  2.  ^              # start of a line 
  3.  \[font         # the font tag 
  4.  (?:=(?P<size>  # optional [font=+size] 
  5.  [-+][0-9]{1,2} # size specification 
  6.  ))? 
  7.  \]             # end of tag 
  8.  (.*?)          # text between the tags 
  9.  \[/font\]      # end of the tag 
  10.  """, re.DEBUG|re.VERBOSE|re.DOTALL)  

另附name match: 
Python代码   收藏代码
  1. >>> p = re.compile(r'(?P<word>\b\w+\b)')  
  2. >>> m = p.search( '(((( Lots of punctuation )))' )  
  3. >>> m.group('word')  
  4. 'Lots'  


3.generator object 
可以节省内存,但是只能使用一次 

4.同时yield列表中的项和序号。 
Python代码   收藏代码
  1. >>> a = ['a''b''c''d''e']  
  2. >>> for index, item in enumerate(a): print index, item  


5.iter() can take a callable argument 

Python代码   收藏代码
  1. def seek_next_line(f):  
  2.     for c in iter(lambda: f.read(1),'\n'):  
  3.         pass  


The iter(callable, until_value) function repeatedly calls callable and yields its result until until_value is returned. 

6.Decorators 
下面的评论中有人说这已经不算太hidden了 

7.yield中send的使用 

8.
Python代码   收藏代码
  1. a = [1,2,3,4,5]  
  2. >>> a[::2]  # iterate over the whole list in 2-increments  
  3. [1,3,5]  

反转
Python代码   收藏代码
  1. >>> a[::-1]  
  2. [5,4,3,2,1]  

对比
Python代码   收藏代码
  1. >>> list(reversed(range(4)))#这种方法返回的是iterator  
  2. [3210]   


9. 默认参数可能会变 
Python代码   收藏代码
  1. >>> def foo(x=[]):  
  2. ...     x.append(1)  
  3. ...     print x  
  4. ...   
  5. >>> foo()  
  6. [1]  
  7. >>> foo()  
  8. [11]  
  9. >>> foo()  
  10. [111]  

Instead, you should use a sentinel value denoting "not given" and replace with the mutable you'd like as default: 

Python代码   收藏代码
  1. >>> def foo(x=None):  
  2. ...     if x is None:  
  3. ...         x = []  
  4. ...     x.append(1)  
  5. ...     print x  
  6. >>> foo()  
  7. [1]  
  8. >>> foo()  
  9. [1]  

默认参数不过是函数的一个属性foo.func_defaults而已,因此对于list类型的可能会变动 

10.defaultdict可以增强dict 
Python代码   收藏代码
  1. >>> s = [('yellow'1), ('blue'2), ('yellow'3), ('blue'4), ('red'1)]  
  2. >>> d = defaultdict(list)  
  3. >>> for k, v in s:  
  4. ...     d[k].append(v)  
  5. ...  
  6. >>> d.items()  
  7. [('blue', [24]), ('red', [1]), ('yellow', [13])]  


相当于 
Python代码   收藏代码
  1. >>> d = {}  
  2. >>> for k, v in s:  
  3. ...     d.setdefault(k, []).append(v)  


对于列表中的每个key,如果该defaultdict中不存在,会使用default_factory来创建该值 

11.for..else 

对于丑陋的代码 
Python代码   收藏代码
  1. found = False  
  2. for i in foo:  
  3.     if i == 0:  
  4.         found = True  
  5.         break  
  6. if not found:  
  7.     print("i was never 0")  


可以使用下面代码来替代 
Python代码   收藏代码
  1. for i in foo:  
  2.     if i == 0:  
  3.         break  
  4. else:  
  5.     print("i was never 0")  


else在for循环从来没有break时调用,有人提议这个关键字else实际上用finally更合适。 

12.值替换,“,”隐含的构成了一个tuple 
Python代码   收藏代码
  1. >>> a = 10  
  2. >>> b = 5  
  3. >>> a, b  
  4. (105)  
  5.   
  6. >>> a, b = b, a  
  7. >>> a, b  
  8. (510)  


13. 和 a ? b : c 等价的if else 语法


Python代码   收藏代码
  1. >>> a = 1 if 2>3 else 4  
  2. >>> a
  3. 4



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值