I want to find sum of Cartesian elements.
My Cartesian list is :[ ('1','2'),('3','4') ]
I want to find the sum of 1+2
and 3+4
and store it into another list.
I want to find sum of Cartesian elements.
My Cartesian list is :[ ('1','2'),('3','4') ]
I want to find the sum of 1+2
and 3+4
and store it into another list.
x = [ ('1','2'),('3','4') ] # Your list
y = [int(a)+int(b) for a,b in x] # y is the sum you want
The second line is a list comprehension that iterates over every element in your list.
Each element is a tuple. By assigning a,b
to that tuple, the first element of the tuple goes in a
and the second in b
.
We convert a
and b
from strings to integers and we add these integers.
(You mention "Cartesian list", but in Python terminology, each element is just a tuple. Perhaps you mean that a Cartesian product of two lists would typically result in a list of tuples.)
EDIT: Another approach, based on @U10-Forward's answer below, is y = map(sum, map(lambda e: map(int, e), x))
You could also use map
as well:
l = [ ('1','2'),('3','4') ]
print(list(map(lambda x: int(x[0]) + int(x[1]), l)))
Using a namedtuple
will allow you to add clarity to your code
Since you already have a list of string tuples
my_list = [('1', '2'), ('3', '4')]
You can first convert them to int
my_list = [(int(x), int(y)) for (x, y) in my_list]
Then introduce a namedtuple
my_list = [Point(x, y) for (x, y) in my_list]
Now your list looks something like this:
[Point(x=1, y=2), Point(x=3, y=4)]
And doing summation of x and y for each Point should be as easy as
sum_of_x_y = [point.x + point.y for point in my_list]
Output:
[3, 4] # sum_of_x_y