Let's say I have to add 2 n-dimensional vectors. What is the pythonic way to add them directly?
For example in R^3, but not limited to R^3,
a = (123.45, 23.45, 1.0)
b = (45.678, 56.78, 5.0)
(Get (169.128, 80.23, 6.0)
)
Let's say I have to add 2 n-dimensional vectors. What is the pythonic way to add them directly?
For example in R^3, but not limited to R^3,
a = (123.45, 23.45, 1.0)
b = (45.678, 56.78, 5.0)
(Get (169.128, 80.23, 6.0)
)
If you try the obvious, you get a generator:
So you can convert it to tuple directly:
In any case, I recommend that you use NumPy instead :
Try with :
Another way using modulo
operator
eitertools
:Using the supplied example:
Another Pythonic way :
map
takes one element from each of the iterables passed to it, which saves the zip.In Python 3.x, map returns a
generator
.In Python 2.x it could be used
itertools.imap
instead ofmap
to always have a consistent result and not generate an intermediate list.Result
In principle:
Now in python3 you will get a generator, so if you want to get a tuple or a list:
The Python programming language is one of the most used in the scientific and educational field and that is due to its specific libraries and APIs for everything related to scientific calculation, I recommend that you enter SciPy and review this great gallery of very interesting libraries among which is NumPy , which was already recommended to you, and Matplotlib which is also very useful for what you want to do, it's just a matter of doing a little research in its documentation and see which one is closest to what you want to do.
Remember that one of the advantages of Python is the large number of libraries that solve many of the problems that we face in the educational and work environment. Whenever you have to do something specific, surely someone has already created a library that, when used, will most likely help you minimize the time to solve the problem.