简体   繁体   中英

How to multiply pair-wise tuple list

I know how to multiply the elements of a single tuple:

tup = (2,3)
tup[0]*tup[1]
6

My question is how do you multiply the elements of several tuples using a for loop?

example: How do I get x = (4,5,6) when x = ((2,2), (5,1), (3,2)) ?

像这样的东西:

tuple(a*b for a, b in x)

for tuples of any length, one line script:

>>> tpl = ((2,2), (5,1), (3,2,4))
>>> tuple(reduce(lambda x, y: x*y, tp) for tp in tpl)
(4, 5, 24)
>>> 
x = ((2, 2), (5, 1), (3, 2))
y = ((2, 3), (2, 3, 5), (2, 3, 5, 7))

def multiply_the_elements_of_several_tuples_using_a_for_loop(X):
    tuple_of_products = []

    for x in X:
        product = 1

        for element in x:
            product *= element

        tuple_of_products.append(product)

    return tuple(tuple_of_products)

print(multiply_the_elements_of_several_tuples_using_a_for_loop(x))
print(multiply_the_elements_of_several_tuples_using_a_for_loop(y))

Output:

(4, 5, 6)
(6, 30, 210)

If you want to use it on tuples of any length:

tuple(product(myTuple) for myTuple in ((2,2), (5,1), (3,2)))

where

def product(cont):
  base = 1
  for e in cont:
    base *= e
  return base

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM