如何减少 Python 3 中的元组列表?
How do you reduce a list of tuples in Python 3?
问题
输入:
input_list = [(1, 2), (1, 4), (1, 6)]
预期输出:
(3, 12)
我试过了
print(reduce(lambda a, b: (a[0] + b[0], a[1] + b[1]), input_list))
和
print(reduce(lambda (a, b), (c, d): (a + c, b + d), input_list))
由于语法无效,两者都失败了。
在Python3中,reduce
从builtins
移动到functools
,所以需要from functools import reduce
.
问题
输入:
input_list = [(1, 2), (1, 4), (1, 6)]
预期输出:
(3, 12)
我试过了
print(reduce(lambda a, b: (a[0] + b[0], a[1] + b[1]), input_list))
和
print(reduce(lambda (a, b), (c, d): (a + c, b + d), input_list))
由于语法无效,两者都失败了。
在Python3中,reduce
从builtins
移动到functools
,所以需要from functools import reduce
.