Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. The following doesn't work since delta is disposed after the first iteration.

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.

like image 354
Lingxi Avatar asked Oct 23 '25 16:10

Lingxi


1 Answers

Use zip() and map() functions to apply the sum() on each column:

x, y = map(sum, zip(*delta))
like image 54
Mazdak Avatar answered Oct 26 '25 05:10

Mazdak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!