Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么Python';s reduce在对列表求和时引发类型错误?_Python_Python 2.7 - Fatal编程技术网

为什么Python';s reduce在对列表求和时引发类型错误?

为什么Python';s reduce在对列表求和时引发类型错误?,python,python-2.7,Python,Python 2.7,我的印象是,如果我使用reduce,我将得到列表中元素的总和,如下所示: reduce(lambda x, y: x[0]+y[0], [[1],[2],[3],[4],[5]]) 然而,我得到的错误是: TypeError:“int”对象没有属性“\uuuu getitem\uuuu” 在这种情况下,reduce在做什么?如果我真的想总结一下,避免for循环的最佳方法是什么?实际上没有太多理由将所有内容都放在子列表中。这才是你真正想要的 reduce(lambda x, y: x+y, [

我的印象是,如果我使用
reduce
,我将得到列表中元素的总和,如下所示:

reduce(lambda x, y: x[0]+y[0], [[1],[2],[3],[4],[5]])
然而,我得到的错误是:

TypeError:“int”对象没有属性“\uuuu getitem\uuuu”

在这种情况下,reduce在做什么?如果我真的想总结一下,避免
for
循环的最佳方法是什么?

实际上没有太多理由将所有内容都放在子列表中。这才是你真正想要的

reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
如果您所做的只是对列表中的元素求和,那么Python有一个内置的函数

sum([1, 2, 3, 4, 5])
如果您确实有理由需要列表列表,那么您也需要将累积值作为列表。可以这样想:传递给
reduce
的函数通常应该返回一个与第一个参数相同的“type”(这里非常宽松地使用“type”一词)值,因为它稍后将作为第一个参数传递给另一个调用

reduce(lambda x, y: [x[0]+y[0]], [[1], [2], [3], [4], [5]])

如果要这样使用reduce,则必须提供初始值:

>>> list_of_lists = [[1],[2],[3],[4],[5]]
>>> reduce(lambda x, y: x+y[0], list_of_lists, 0)
15
但不要为此使用
reduce
。只需使用内置的:

>>> sum(n for sublist in list_of_lists for n in sublist)
15
>>> sum(n for [n] in list_of_lists)  # enforcing 1-element sublists
15

我把我的问题简化成了一个数字列表,但我必须使用这种格式。这是有道理的,一个将保存减少作为一个列表。。。