標籤:map lambda python reduce
#!/usr/bin/env python3# -*- coding: utf-8 -*-def f(x):return x * xr = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])# 結果r是一個Itertator,是惰性序列# 通過list()函數讓它把整個序列都計算出來並返回一個listprint(list(r))# [1, 4, 9, 16, 25, 36, 49, 64, 81]print(list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])))# ['1', '2', '3', '4', '5', '6', '7', '8', '9']from functools import reducedef add(x, y):return x + yprint(reduce(add, [1, 3, 5, 7, 9]))# 25from functools import reducedef fn(x, y):return x * 10 + yprint(reduce(fn, [1, 3, 5, 7, 9]))# 13579# str2int的函數from functools import reducedef str2int(s):def fn(x, y):return x * 10 + ydef char2num(s):return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]return reduce(fn, map(char2num, s))print(str2int('13579'))# 13579from functools import reducedef char2num(s):return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]def str2int(s):return reduce(lambda x, y: x * 10 + y, map(char2num, s))print(str2int('12354'))# 12354# 練習def normalize(name):return name[:1].upper() + name[1:].lower()L1 = ['adam', 'LISA', 'barT']L2 = list(map(normalize, L1))print(L2)# ['Adam', 'Lisa', 'Bart']from functools import reducedef prod(L):def fn(x, y):return x * yreturn reduce(fn, L)print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))# 3 * 5 * 7 * 9 = 945from functools import reducedef str2float(s):def char2num(s):return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]def add1(x, y):return x * 10 + yindex = s.find('.')t = len(s) - index - 1return reduce(add1, map(char2num, s.replace('.', ''))) / pow(10, t)print('str2float(\'123.456\') =', str2float('123.456'))# str2float('123.456') = 123.456
#!/usr/bin/env python3# -*- coding: utf-8 -*-from functools import reduceCHAR_TO_INT = { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}def str2int(s): ints = map(lambda ch: CHAR_TO_INT[ch], s) return reduce(lambda x, y: x * 10 + y, ints)print(str2int('0'))print(str2int('12300'))print(str2int('0012345'))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('0'))print(str2float('123.456'))print(str2float('123.45600'))print(str2float('0.1234'))print(str2float('.1234'))print(str2float('120.0034'))
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
Python學習筆記 - map reduce