列表生成式練習
請修改列表生成式,通過添加if語句保證列表生成式能正確執行:
L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = []
for x in L1:
if instance(x):
L2.append(x)
print(L2)
map/reduce練習
利用map()函數,把用戶輸入的不規范的英文名字,變為首字母大寫,其他小寫的規范名字。
輸入:['adam',‘LISA', 'barT'], 輸出:['Adam','Lisa','Bart']:
def normalize(name):
return "%s" % (name[:1].upper() + name[1:])
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
Python提供的sum()函數可以接受一個list並求和,請編寫一個prod()函數,可以接受一個list並利用reduce()求積:
from functools import reduce
def prod(L):
def product(x, y):
return x * y
return reduce(product, L)
print(prod(L))
利用map和reduce編寫一個str2float函數,把字符串’123.456’轉換成浮點數123.456:
str2float函數實現轉自https://github.com/michaelliao/learnpython3/blob/master/samples/functional
from functools import reduce
CHAR_TO_FLOAT = {
'0': 0,
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'.': -1
}
def str2float(s):
nums = map(lambda ch: CHAR_TO_FLOAT[ch], s)
point = 0
def to_float(f, n):
nonlocal point
if n == -1:
point = 1
return f
if point == 0:
return f * 10 + n
else:
point = point * 10
return f + n / point
return reduce(to_float, nums, 0.0)
print("str2float('\123.456\') = ", str2float('123.456'))
filter練習
回數是指從左向右讀和從右向左讀都是一樣的數,例如12321,909。請利用filter()濾掉非回數:
def is_palidrome(n):
I, m = n, 0
while I:
m = m*10 + I%10
I = I // 10 #返I的整數部分,拋棄余數
return(n == m)
output = filter(is_palindrome, range(1, 1000))
print(output)
sort()函數練習
假設我們用一組tuple表示學生名字和成績:
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
請用sorted()對上述列表分別按名字排序:
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def by_name(t):
return t[0] #返回名字
L2 = sorted(L, key=by_name)
print(L2)
再按成績從高到低排序:
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def by_name(t):
return t[1] #返回成績
L2 = sorted(L, key = by_name, reverse = True)
print(L2)
請編寫一個decorator, 能在函數調用的前后打印出'begin call'和'end call'的日志:
轉自http://blog.csdn.net/be_your_king/article/details/69938237
import functools
def log(func):
@functools.wraps(func) # wrap '__name__'
def wrapper(*args, **kw):
print("begin call [%s]" % (func.__name__))
func_tmp = func(*args, **kw)
print("end call [%s]" % (func.__name__))
return func_tmp
return wrapper
@log # 借助Python的@語法,把decorator置於函數的定義處
def hello():
print("hello")
hello()
