2011-11-12 8 views
2

を乗算するために、私は単一のタプルの要素を掛け合わせる方法を知っている:どのように対にタプルのリストに

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

私の質問はどのようにループのために使用して複数のタプルの要素を掛けないのですか?

例:x = ((2,2), (5,1), (3,2))の場合、x = (4,5,6)はどうすれば入手できますか?

答えて

5

このような何か:

tuple(a*b for a, b in x) 
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) 
+0

プラス任意の長さの内側のタプルを処理するための –

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 
2

、1行スクリプト:

>>> tpl = ((2,2), (5,1), (3,2,4)) 
>>> tuple(reduce(lambda x, y: x*y, tp) for tp in tpl) 
(4, 5, 24) 
>>> 
関連する問題