1. 异常处理
# three except methods
try:
a = 1/0
except Exception,e:
print Exception,":",e
import traceback
try:
a = 1/0
except:
traceback.print_exc()
f=open("exc.log", 'a')
traceback.print_exc(file=f)
f.flush()
f.close()
import sys
try:
a = 1/0
except:
info = sys.exc_info()
print info[0],":",info[1]
输出:
C:\Python27\python-code>python learning-6.py
<type 'exceptions.Exception'> : integer division or modulo by zero
Traceback (most recent call last):
File "learning-6.py", line 9, in <module>
a = 1/0
ZeroDivisionError: integer division or modulo by zero
<type 'exceptions.ZeroDivisionError'> : integer division or modulo by zero
2 map/reduce/filter
filter() 函数:
filter 函数的功能相当于过滤器。调用一个布尔函数bool_func来迭代遍历每个seq中的元素;返回一个使bool_seq返回值为true的元素的序列。
# filter
a = [0,1,2,3,4,5]
b1 = filter(lambda x:x>2, a)
print b1
b2 = filter(None, a)
print b2
map() 函数:
map函数func作用于给定序列的每个元素,并用一个列表来提供返回值。
# map
b3 = map(lambda x:x**2, a)
print b3
c = [10, 11, 12, 13, 14, 15]
b4 = map(lambda x, y: x*y, a, c)
print b4
reduce() 函数:
reduce函数,func为二元函数,将func作用于seq序列的元素,每次携带一对(先前的结果以及下一个序列的元素),连续的将现有的结果和下一个值作用在获得的随后的结果上,最后减少我们的序列为一个单一的返回值。
# reduce
b5 = reduce(lambda x,y:x+y, a)
print b5
输出:
[3, 4, 5]
[1, 2, 3, 4, 5]
[0, 1, 4, 9, 16, 25]
[0, 11, 24, 39, 56, 75]
15
3. set类型
# set
x = set(['apple', 'nokia', 'samsung', 'h'])
y = set('hello')
print x
print y
print x & y
print x | y
print x - y
print x ^ y
# use set to delete repeated element in list
a = [1,2,3,4,5,6,7,2]
b = set(a)
print b
c = [i for i in b]
print c
#basic operations
b.add('x')
b.update(['a','b','c'])
print b
b.remove('x')
print b
print len(b)
print 'b' in b
print 'b' not in b
4. 元组转列表
# dict.fromkeys()
myDict = dict.fromkeys('hello', True)
print myDict
from collections import defaultdict
# collections.defaultdict() set value type
s = [('yellow', 1), ('blue', 2), ('yellow', 3)]
d = defaultdict(list)
for k, v in s:
d[k].append(v)
print d.items()
{'h': True, 'e': True, 'l': True, 'o': True}
[('blue', [2]), ('yellow', [1, 3])]