使用 reduce() 添加自定义对象

Add custom objects with reduce()

我正在尝试从自定义对象列表中添加一个字段的值,但我无法在 Python 中使用 reduce() 函数找到解决方案:

final_time = init_time + reduce(lambda x, y: x.time_coef + y.time_coef, list_of_paths)

可迭代对象是带有自定义字段 (time_coef) 的自定义对象 (shapely.LineString) 的列表。

据我了解,reduce 可以进行第一次加法,但第二次迭代失败,因为它试图将 .time_coef 属性获取到前一次加法的结果(浮点数)。

有什么方法可以避免这种情况,还是我应该迭代列表而不是使用 reduce?

您可以将 sum 与列表理解结合使用

final_time = init_time + sum(x.time_coef for x in list_of_paths)

这里的一般模式是初始化累加器,其基值与您的回调类型return相同,因此第一次调用 reduce 函数不会隐式传递两个对象:

reduce(lambda a, i: a + i.time_coef, lst, 0)
#             initialise your accumulator ^