python - reduce(x+y, xs) 和 sum(xs) 在 python 中不等价?

标签 python sum tuples reduce equational-reasoning

但是,从函数等式的角度来看,我希望两者的含义相同:

x = [1, 2, 3]
y = ['a', 'b', 'c']

reduce(lambda x, y: x + y, zip(x, y))  # works

sum(zip(x, y))  # fails

为什么 sum 在这里失败了?

最佳答案

实际问题是,sum的默认起始值​​。引用 documentation ,

Sums start and the items of an iterable from left to right and returns the total. start defaults to 0. The iterable‘s items are normally numbers, and the start value is not allowed to be a string.

但是,如果是 reduce ,如果没有给出可选的起始值,它将使用可迭代对象中的第一个值作为初始值设定项。所以,reduce其实是这样评价的

( ( (1, 'a') + (2, 'b') ) + (3, 'c') )

sum假设起始值为 0,它会这样计算,

0 + (1, 'a') + (2, 'b') + (3, 'c')

在这种情况下,它会尝试添加 0有一个元组,这就是为什么你得到

TypeError: unsupported operand type(s) for +: 'int' and 'tuple'

要解决这个问题,将一个空元组传递给 sum开始,像这样

>>> sum(zip(x, y), tuple())
(1, 'a', 2, 'b', 3, 'c')

现在,初始值是一个空元组,评估是这样发生的

() + (1, 'a') + (2, 'b') + (3, 'c')

注意:在这两种情况下,都会创建多个中间元组。为避免这种情况,我建议展平数据并将其传递给 tuple构造函数作为生成器表达式,像这样

>>> tuple(item for items in zip(x, y) for item in items)
(1, 'a', 2, 'b', 3, 'c')

关于python - reduce(x+y, xs) 和 sum(xs) 在 python 中不等价?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28625184/

相关文章:

javascript - scrapy-splash 无法呈现此页面 - 未呈现动态内容?

python - 如何在 Django 模板中使用 break 和 continue?

javascript:如何从复选框获取标题属性值?

python - 我会称之为高级元组操作吗?

python - 如何从 Pandas Dataframe 创建多个元组列表

python - 使用 pyplot 注释 x 轴下方的垂直线

r - 在恒定的日历周间隔内求和

java - JAVA中有什么方法可以对元素求和吗?

python - 如何将元组中的某些项目从列表转换为 float ?

python - 用一个副本遍历所有列表