[英]Turn iterable of tuple into iterables of each element (Python)
I have an iterable delta
that generates tuple of two numbers (dx, dy)
, and I want to compute the sum of each. 我有一个可迭代的delta
,它生成两个数字的元组(dx, dy)
,我想计算每个数的总和。 The following doesn't work since delta
is disposed after the first iteration. 以下不起作用,因为在第一次迭代后处理delta
。
x = sum(dx for dx, dy in delta)
y = sum(dy for dx, dy in delta)
Any idea? 任何想法? I'm thinking in the direction of somehow turning delta
into two iterables of dx
and dy
, but have reached nothing so far. 我正在考虑以某种方式将delta
变成dx
和dy
两个迭代,但到目前为止还没有达到任何目标。
使用zip()
和map()
函数在每列上应用sum()
:
x, y = map(sum, zip(*delta))
This ought to do it! 这应该做到的!
ysum = 0
xsum = 0
for dx, dy in delta:
xsum += dx
ysum += dy
The idea with a generator is that you can exhaust it once, so why not just do all of your math in one go? 使用发生器的想法是你可以用尽一次,所以为什么不一次完成所有的数学运算呢?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.