functools reduce() gives TypeError: 'int' object is not subscriptable

functools reduce() gives TypeError: 'int' object is not subscriptable

我在使用 functools.reduce() 时遇到问题。 它returns int 对象不可下标

total_population = functools.reduce(lambda a, b: a[0] + b[0], mid_points)

变量'mid_points'元组列表:示例如下图

但是当我尝试上面的代码行时:

li = [(1,"a"), (2,"b")]

它给出了正确的输出,即 3

请帮忙!我在做什么?

reduce 的结果需要是归约函数的有效 输入 ;您的缩减函数需要一个至少包含一个元素的序列,但您返回的是 int。只需将代码更改为:

[total_population] = functools.reduce(lambda a, b: (a[0] + b[0],), mid_points)

添加一层 tuple 包装以便索引继续工作,并且 。如果 mid_points 是单个元素,这将中断,所以如果可能的话:

total_population, *_ = functools.reduce(lambda a, b: (a[0] + b[0],), mid_points)

稍微安全一些,因为它只是将结果中的任何额外元素捕获到忽略的 list.

另一种方法(感谢@deceze 提醒我)是给 reduce 一个起始值,因此 a 始终是 int,无论是在第一次调用还是随后的所有调用中调用:

total_population = functools.reduce(lambda a, b: a + b[0], mid_points, 0)

reduce 的最后一个参数是第一个 a,所有后续的 a 都是先前调用的结果。当然这也可以简化成第三种方式,完全避免reduce

from operator import itemgetter

total_population = sum(map(itemgetter(0), mid_points))

# Or without an import, but ever-so-slightly slower:
total_population = sum(pt[0] for pt in mid_points)

因为你真的只需要做两件事;提取每个输入的第一个元素,并对它们求和。