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
其它集合
- namedtuple() # 用指定的域创建元组子类的工厂函数
- deque # 类似list的容器,快速追加以及删除在序列的两端
- Counter # 统计哈希表的dict子类
- OrderedDict # 记录实体添加顺序的dict子类
- 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