2

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.

Joshua Fox
  • 18,704
  • 23
  • 87
  • 147
  • 1
    Does this answer your question? [Sum of elements stored inside a tuple](https://stackoverflow.com/questions/29471260/sum-of-elements-stored-inside-a-tuple) – RoadRunner Apr 29 '20 at 05:30
  • It’s probably important to realise that you have two separate problems β€” converting your original tuples of strings into tuples of integers (or floats?) and subsequently adding those up. In fact I suspect that you probably really want to convert from strings to numbers when you are creating them from user input (or wherever) since the real data structure that represents cartesian points would certainly be numeric tuples. – Andrew Jaffe Apr 29 '20 at 17:46

3 Answers3

5
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))

Joshua Fox
  • 18,704
  • 23
  • 87
  • 147
1

You could also use map as well:

l = [ ('1','2'),('3','4') ]
print(list(map(lambda x: int(x[0]) + int(x[1]), l)))
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

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