Python Forum
How to multiply tuple values in array?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to multiply tuple values in array?
#1
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' .
Reply
#2
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.
Reply
#3
https://stackoverflow.com/questions/1781...y-a-scalar.

look on this thread here is solution for your problem
Reply
#4
.... 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]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  I can't multiply within my code TypicalBrummie 1 1,654 Feb-06-2018, 08:05 PM
Last Post: boring_accountant
  Array NaN values? ValueError: continuous format is not supported metalray 3 6,370 Jan-05-2018, 08:56 AM
Last Post: metalray

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020