如何乘以成对的元组列表

时间:2011-11-12 16:27:13

标签: python

我知道如何将单个元组的元素相乘:

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

我的问题是如何使用for循环将多个元组的元素相乘?

示例:如何在x = (4,5,6)时获得x = ((2,2), (5,1), (3,2))

4 个答案:

答案 0 :(得分:5)

这样的事情:

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

答案 1 :(得分:2)

任何长度的元组,一行脚本:

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

答案 2 :(得分:1)

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

输出:

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

答案 3 :(得分:1)

如果你想在任何长度的元组上使用它:

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

,其中

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