pythonic examples

来源:互联网 发布:旅行车 知乎 编辑:程序博客网 时间:2024/04/30 15:28

pythonic examples

文章分类:Python编程

 

1. 百分号的使用:

通常我们都是这样格式化字符串的:

 

Python代码
  1. print 'hello world programme by %s' % 'python'  

 

 但是如果格式化的字符串中有很多%s,那么程序的可读性就会依靠于%后面 的变量名起得是否好了。

这个时候有一种用dict来格式化的%,我觉得很有用,尤其是在记log的 时候,作为log的格式,可读性非常高。

代码如下:

 

Java代码
  1. #字符串  
  2. value = {'what''hello, world''language''python'}  
  3. print '%(what)s, %(language)s' % value  
  4. #也可以包含int的  
  5. value = {'name''jianpx''age'23}  
  6. print '%(name)s 's age is  %(age)i' % value  

 

 

2. 用两个元素之间有对应关系的list构造一个dict:

运用zip可以非常简单的实现:

 

Python代码
  1. names = ['jianpx''yue']  
  2. ages = [2340]  
  3. m = dict(zip(names,ages))  

 

 zip的使用可以help(zip)或者查看官方文档。

 

3.  交换两个值:

在其他语言可能要一个临时变量和三句话:

temp = a

a = b

b = tem

但是在python,一句就ok了,而且不需要临时变量:

a,b = b,a

右边的b,a 其实可以理解成一个tuple。

 

4. 数量多的字符串相连用join:

python字符串效率问题之一就是在连接字符串的时候使用‘+’号,例如 s = 's1' + 's2' + 's3' + ...+'sN',总共将N个字符串连接起来,但是使用+号的话,python需要申请N-1次内存空间,然后进行字符串拷贝。原因是字符串对象PyStringObject在python当中是不可变对象,所以每当需要合并两个字符串的时候,就要重新申请一个新的内存空间(大小为两个字符串长度之和)来给这个合并之后的新字符串,然后进行拷贝。所以用+号效率非常低。建议在连接字符串的时候使用字符串本身的方法join(list),这个方法能提高效率,原因是它只是申请了一次内存空间,因为它可以遍历list中的元素计算出总共需要申请的内存空间的大小,一次申请完。所以上面的例子可以写成s = ''.join(['s1','s2',....,'sN'])

 

例子是:

 

Python代码
  1. #以前是这样写的  
  2. fruits = ['apple''banana']  
  3. result = ''  
  4. for f in fruits:  
  5.     result += f  
  6.   
  7. #现在可以这样:  
  8. fruits = ['apple''banana']  
  9. result = ''.join(fruits)  

 

5. 判断一个key是否在一个dict里面:

以前很经常犯的一个mistake是这样做:

 

Python代码
  1. if key in dict_example:  
  2.     do something  

 现在要这样写,就不用使用in操作了。

 

Python代码
  1. if dict_example.has_key(key):  
  2.     do something  
 

6. 去掉list中的重复元素:

 

Python代码
  1. old_list = [1,1,1,3,4]  
  2. new_list = list(set(old_list))  

 

7. 如果对两个都没有重复元素的列表对象,要判断某个元素是否在列表里面的话,当这个列表很大的时候,用set会比list

的性能要好,因为对于list,本身允许重复元素存在,所以它不是用hash实现的,但是set不一样,它不允许重复元素,看了python源代码,从set的实现源码setobject.c 中查找key的函数

static setentry *

set_lookkey(PySetObject *so, PyObject *key, register long hash)    

的接口可以看出它真的使用hash去实现的。   

所以对于in操作,set的实现是计算这个元素的hash值然后判断,理论上可以达到O(1)

 

 

8. 读文件操作:

以前是这样写的:

 

Python代码
  1. #默认文件存在,不处理Exception的情况  
  2. f = open('filename''r')  
  3. while 1:  
  4.     line = f.readline()  
  5.     if not line:  
  6.         break  
  7.     print line  
  8.   
  9. if f:  
  10.     f.close()  

 

用with关键字可以这样简写了,

 

Python代码
  1. from __future__ import with_statement  
  2. with open('filename','r') as f:  
  3.     for line in f:  
  4.         print line  

具体关于with的可以参考我的这篇文章:http://jianpx.javaeye.com/blog/505469

 

 

9.  输出数组的index和值:

以前是要这样写的:

 

Python代码
  1. l = [1,3,4]  
  2. for i in xrange(len(l)):  
  3.     print '%d, %d' % (i , l[i])  

现在可以用enumerate函数帮助你简写:

Java代码
  1. l = [1,34]  
  2. for index, value in enumerate(l):  
  3.     print '%d, %d' % (index, value)  

 

10.  关于使用map、filter、reduce的例子网上很多,这里不细说了,它们的使用也是pythonic的examples

 

11. 分隔一个字符串,去里面的元素,但是空白字符串不要:

例如, names = 'jianpx, yy, mm, , kk'

 

Python代码
  1. names = 'jianpx, mm, yy, , kk'  
  2. name_list = names.split(',')  
  3. result = []  
  4. for name in name_list:  
  5.     if name:  
  6.         result.append(name)  

 

现在是这样写的:

 

Python代码
  1. names = 'jianpx, yy, mm, , kk'  
  2. result = [name for name in names.split(','if name.strip()]  

 

12. 模拟c语言中的  a?b:c

在python里面可以这样做:

 

Python代码
  1. return_value = True if a == 1 else False  

 从而代替了这样的代码:

 

Python代码
  1. if a == 1:  
  2.     return_value = True  
  3. else   
  4.     return_value = False  

 

13 用Decorator抽离公用代码或者解耦

例如要对一个函数做cache,对一个操作限制权限,如果需求随时可能变化,就是说有可能不需要做cache或者不需要做权限的时候,你如果把实现放到这些函数体里面,那么这时你必须把这些代码删除,而且要很小心。但是如果你用Decorator去做的话, 只要删除函数头顶上的@那一行就可以了。Django经常用这种方法做权限控制。

熟悉decorator的应该都很容易理解。

 

 

 

现在就总结了这些,如果大家有其他的pythonic examples,欢迎留言更新或者拍砖!

最后上一段python的禅:

 

 

Python代码
  1. Python 2.5.2 (r252:60911, Jan 24 201014:53:14)   
  2. [GCC 4.3.2] on linux2  
  3. Type "help""copyright""credits" or "license" for more information.  
  4. >>> import this  
  5. The Zen of Python, by Tim Peters  
  6.   
  7. Beautiful is better than ugly.  
  8. Explicit is better than implicit.  
  9. Simple is better than complex.  
  10. Complex is better than complicated.  
  11. Flat is better than nested.  
  12. Sparse is better than dense.  
  13. Readability counts.  
  14. Special cases aren't special enough to break the rules.  
  15. Although practicality beats purity.  
  16. Errors should never pass silently.  
  17. Unless explicitly silenced.  
  18. In the face of ambiguity, refuse the temptation to guess.  
  19. There should be one-- and preferably only one --obvious way to do it.  
  20. Although that way may not be obvious at first unless you're Dutch.  
  21. Now is better than never.  
  22. Although never is often better than *right* now.  
  23. If the implementation is hard to explain, it's a bad idea.  
  24. If the implementation is easy to explain, it may be a good idea.  
  25. Namespaces are one honking great idea -- let's do more of those!