Python Forum

Full Version: How to multiply tuple values in array?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi guys. I have stumbled on a issue where I can't multiply the elements in a tuple. Lets say we have [(x1, y1),(x2, y2)], I need the output like this: [(x1 * y1), (x2 * y2)]

Here is the code:

from itertools import product

arr = 0
val_x = []
val_y = []
n = int(input('n = '))

def multiply(product, *nums):
    factor = product
    for num in nums:
        factor *= num
    return factor

if __name__ == "__main__":

    for x in range(n ** 2):
        for y in range(n ** 2):
            if y == 0:
                arr += 1
        if arr == 1:
            val_x.append(bin(x)[2:].zfill(n))
            val_y.append(bin(x)[2:].zfill(n))
        arr = 0

    res = list(product(val_x, val_y))

    print(f'Input x,y = {res}')
    print(f'Output z = {multiply(*res)}')
I get the following error: TypeError: can't multiply sequence by non-int of type 'tuple' .
If you are literally just looking to get from [(x1, y1),(x2, y2)] to [(x1 * y1), (x2 * y2)], you can do it like this since you know each tuple will have two values:

x=[(1, 3), (2,4)]
new=[]
for pair in x:
    new.append(pair[0] * pair[1])
print(new)
Output:
[3, 8]
I'm not sure that's actually what you are looking for, though.
https://stackoverflow.com/questions/1781...y-a-scalar.

look on this thread here is solution for your problem
.... Doh
arr = [(1, 3), (5, 7)]
arr = [i[0]*i[1] for i in [list(col) for col in zip(*arr)]]
print(arr)
Output:
[5, 21]