[整理]python 小技巧

1.

python有各种各样的容器数据类型,在特定情况下选择python内建的容器如:list和dict。通常更多像如下方式使用:

freqs = {}  
for c in "abracadabra":  
    try:  
        freqs[c] += 1  
    except:  
        freqs[c] = 1


一种更好的方案如下:

freqs = {}  
for c in "abracadabra":  
    freqs[c] = freqs.get(c, 0) + 1 


一种更好的选择 collection类型defautdict:

from collections import defaultdict  
freqs = defaultdict(int)  
for c in "abracadabra":  
    freqs[c] += 1  


其它集合

 
 
  1. namedtuple() # 用指定的域创建元组子类的工厂函数  
  2. deque # 类似list的容器,快速追加以及删除在序列的两端  
  3. Counter # 统计哈希表的dict子类  
  4. OrderedDict # 记录实体添加顺序的dict子类  
  5. defaultdict # 调用工厂方法为key提供缺省值的dict子类 

2.

条件赋值

x = 3 if (y == 1) else 2 
x = 3 if (y == 1) else 2 if (y == -1) else 1 

记住,你可以在任何表达式中使用if-else例如:

(func1 if y == 1 else func2)(arg1, arg2) 
x = (class1 if y == 1 else class2)(arg1, arg2)  
func1, func2是两个函数, class1,class2是两个类

3.

在c语言里 , __FILE__ 和 __LINE__ 给调试提供了很大的方便,python可以通过下面方法替代:

print ("here is :" , sys._getframe().f_lineno )
或者:
import inspect
try :
    c=inspect.currentframe()
    print  c.f_code.co_filename,c.f_lineno,
finally :
    del c


4.二维数组:

#创建一个宽度为3,高度为4的数组
myList = [( [0] * 3) for i inrange(4)]
multilist = [[0 for col in range(3)] for row in range(4)]

 

来源:

1 : http://blog.chinaunix.net/uid-2413049-id-3166028.html

http://sd.csdn.net/a/20120522/2805748.html

3 : http://blog.chinaunix.net/uid-2413049-id-109821.html

http://blog.chinaunix.net/uid-2413049-id-109808.html

4: http://www.cnblogs.com/btchenguang/archive/2012/01/30/2332479.html

4: http://www.jb51.net/article/15716.htm




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值