-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdo_map.py
More file actions
69 lines (44 loc) · 1.48 KB
/
Copy pathdo_map.py
File metadata and controls
69 lines (44 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#!/bin/env python3
# -*- coding:utf-8 -*-
from functools import reduce
def f(x):
return x * x
# use map()将传入的函数依次作用到list的每个元素,返回一个iterator
r = map(f, [1, 2, 3, 4]) # r is Iterator
print(list(r))
print(list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])))
# use reduce()将一个函数作用在list上,并把结果继续和序列的下一个元素做累积计算
def add(x, y): # reduce()函数必接收两个参数
return x + y
print(reduce(add, [1, 3, 5, 7, 9]))
def fn(x, y):
return x * 10 + y
print(reduce(fn, [1, 3, 4, 5, 6]))
def char2num(s): # str 转换为 Int
digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
return digits[s]
print(reduce(fn, map(char2num, '13579'))) # map() and reduce() with togther
# 规范名称
print(list(map(lambda name: name[0].upper() + name[1:].lower(), ['adam', 'LISA', 'barT'])))
# reduce接受list求积
def prod(L):
return reduce(lambda x, y: x * y, L)
# str2int
def str2int(s):
ints = map(lambda ch: CHAR_TO_INT[ch], s)
return reduce(lambda x, y: x * 10 + y, ints)
# str2float
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)