'Python method that sums tuples in a list based on a loop?
I have the following arguments:
a = [(3, 3)]
b = [(2, 0), (1, 0), (0,1), (0,2), (1,1)]
I need to write a function that generates a list of tuples where each element is a unique summation of a and the elements of b. This is my expected result:
c = [(5, 3), (4, 3), (3, 4), (3, 5), (4, 4)]
I am having trouble writing this into a function that will work regardless of what tuple is inputted in a. I can write the code that works on one individual element via the below:
import operator
a = 3, 3
b = 2, 0
result = tuple(map(operator.add, a, b))
How can I turn this into a reproducible function? I have tried several avenues / syntax and believe I am missing something simple.
Solution 1:[1]
If a is always a list of a tuple with two elems, the following should work:
def example(a, b):
toRet = []
op1, op2 = a[0]
for val1, val2 in b:
toRet.append((val1 + op1, val2 + op2))
return toRet
a = [(3, 3)]
b = [(2, 0), (1, 0), (0, 1), (0, 2), (1, 1)]
c = [(5, 3), (4, 3), (3, 4), (3, 5), (4, 4)]
print(f"Output correct: {example(a, b) == c}")
Output
Output correct: True
Process finished with exit code 0
Solution 2:[2]
If a is always guaranteed to be a list of a single tuple you can use this simple list comprehension:
>>> [(a[0][0] + x, a[0][1] + y) for x, y in b]
[(5, 3), (4, 3), (3, 4), (3, 5), (4, 4)]
As a side note, generator expressions and list comprehensions are considered more pythonic when compared to map.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jawand S. |
| Solution 2 | Selcuk |
