如何减少列表中的列表
我的直觉说降低
(从功能上的导入降低)会提供我想要的东西,但我无法在这里使用它来缠绕我的头。
def test_reduce_lists_by_summing_them():
"""
Sum each item from the first list with the same positional item from the subsequent list.
The result is the next first list and appended to the returned result list.
"""
input_ = [[1, 0, 0], [0, 1, 0], [0, 0, 2], [3, 0, 0]]
expected_output = [[1, 1, 0], [1, 1, 2], [4, 1, 2]]
def f(x, y):
"""Return the sum of two positional items"""
return x + y
output = []
for group in zip(input_[0:], input_[1:]):
# Obvisously not working since the first list is not generated but just taken grp[0]
output.append(list(map(f, group[0], group[1])))
assert output == expected_output
My gut says that reduce
(from functools import reduce) would deliver what I'm looking for, yet I can't wrap my head around using it here.
def test_reduce_lists_by_summing_them():
"""
Sum each item from the first list with the same positional item from the subsequent list.
The result is the next first list and appended to the returned result list.
"""
input_ = [[1, 0, 0], [0, 1, 0], [0, 0, 2], [3, 0, 0]]
expected_output = [[1, 1, 0], [1, 1, 2], [4, 1, 2]]
def f(x, y):
"""Return the sum of two positional items"""
return x + y
output = []
for group in zip(input_[0:], input_[1:]):
# Obvisously not working since the first list is not generated but just taken grp[0]
output.append(list(map(f, group[0], group[1])))
assert output == expected_output
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在寻找的是累积:
如果您'愿意使用numpy,它将很简单:
upd demo:
What you're looking for is accumulate:
And if you're willing to use numpy, it would be as simple as:
UPD Demo: