initial [ɪ'nɪʃəl] adj. 最初的;字首的
reduce()
----------
对参数序列中元素进行累积
~~~
functools.reduce = reduce(...)
reduce(function, sequence[, initial]) -> value
~~~
- 参数:`function` -- 函数(只能2个参数!)
- 参数:`sequence` -- 序列(仅1个!)
- 参数:`initial` -- 积累的初始值
- 返回值:函数计算结果
~~~
from functools import reduce
def f(x, y):
return x+y
reduce(f, range(5)) # 10
reduce(f, [1, 2, 3], 5) # 11
~~~
练习
----
1) 接受list并求积
~~~
def product_list(num_list):
for x in num_list:
if not isinstance(x, int) or isinstance(x, float):
num_list.remove(x)
from functools import reduce
return reduce(lambda x, y: x * y, num_list)
print(product_list([1, 2, 3]))
print(product_list([1, 'a', 2, 3]))
~~~
2) 使用`map()`、reduce()将字符串'123.456'转换为浮点数123.456
~~~
CHAR_TO_FLOAT = {
'0': 0,
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'.': '.'
}
def str2float(s):
nums_map = map(lambda x: CHAR_TO_FLOAT[x], s)
index = -1 # 小数位时指数
is_int = True # 是否整数位
def to_float(x, y):
nonlocal index, is_int
if y == '.':
is_int = False
return x
else:
if is_int:
v = x*10 + y
else:
v = x + y*10**index
index -= 1
return v
from functools import reduce
return float(reduce(to_float, nums_map, 0.0))
print(str2float('123.456'))
print(str2float('0'))
print(str2float('1234'))
print(str2float('1.234'))
print(str2float('1.23400'))
print(str2float('0.123'))
print(str2float('.123'))
~~~
- 前言
- Python编程规范
- 编码
- 代码
- 缩进、行宽、引号、空行
- 空格
- 换行
- import
- 注释
- 代码注释
- 文档注释(Docstring)
- 命名规范
- 数据结构
- 变量
- 变量作用域
- 命名空间
- 作用域
- python作用域
- 对象
- 序列
- 可迭代对象
- 迭代器
- 生成器
- 可迭代对象 & 迭代器 & 生成器
- 整数池 & 字符串intern
- 数据类型
- 数字
- int
- float
- NaN
- 四舍五入 & 取整
- 列表
- 元组
- 字典
- 集合
- 字符串
- 字符集&字符编码
- 字符串&字节串
- 字符串函数
- 字符串格式化
- str.format
- Formatted string literals
- format函数
- string.Formatter类
- %
- Format String Syntax
- Format Specification Mini-Language
- fill
- align
- sign
- #
- 0
- width
- grouping_option
- .precision
- type
- locale
- Python3 locale 模块
- 语句
- 运算符
- if/else
- for...in
- while
- break/continue
- 函数
- 函数
- 函数参数
- 递归函数
- 匿名函数
- 高阶函数
- map
- reduce
- filter
- sorted
- 返回函数
- 闭包
- 装饰器
- 函数装饰器
- 带参数的装饰器
- 类装饰器
- 带参数的类装饰器
- 偏函数
- 面向对象
- 类 & 实例
- 属性
- 方法
- 访问限制
- 继承
- 新式类 & 经典类
- MRO
- MixIn
- 模块
- 特殊变量
- 编写模块
- 引入 & 重载
- 搜索模块
- 第三方模块
- 常见模块
- 标准库
- os
- sys
- datetime
- re
- urllib
- time/datetime
- threading
- multiprocessing
- builtins
- help
- range
- enumerate
- 异同
- str() repr() ascii()
- exit()、sys.exit()、os._exit()
- 数据库
- mysql
- 错误、调试、测试
- 异常
- 异常处理
- 自定义异常
- 抛出异常
- 调试
- logging
- pdb
- 线程&&进程
- 线程
- 杂
- python 脚本传参
- python无关
- redis
- mongo
- linux
- mysql简略