python學習六:異常處理、map/reduce/filter內置函數、python集合(set)類型、元組轉列表

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])]



發佈了30 篇原創文章 · 獲贊 1 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章