2014-10-30 16 views
0

我目前有:如何製作數字列表的元組?

def product_of_tuples(nums_list): 
    '''Receives a list of tuples of two or more numbers. Returns 
    a list of the products of the numbers in each tuple. (Note: 
    the product of a sequence of numbers is obtained by multiplying 
    them together.)''' 

    result = [] 
    for numbers in nums_list: 
     *# ''' need something here '''* 
     for num in numbers: 
      multi_number = num * num 
     result.append(multi_number) 
    return result 

當運行

print(product_of_tuples([(1, 5), (6, 1), (2, 3, 4)]))預期的輸出應該[5, 6, 24]

任何建議,將不勝感激:)

回答

1

你瘋玩起來內部。由於這是乘法,所以每次需要將累加器重置爲1,然後您需要依次將其乘以每個數。

1
from operator import mul 

def product_of_tuples(nums_list): 
    '''Receives a list of tuples of two or more numbers. Returns 
    a list of the products of the numbers in each tuple. (Note: 
    the product of a sequence of numbers is obtained by multiplying 
    them together.)''' 

    return [reduce(mul, i) for i in nums_list] 
+0

+1我會這麼做的。值得注意的是,在reduce中不需要1中的參數作爲None的初始化程序將導致使用iterable的第一個元素,在這種情況下,由於乘以1是身份函數,所以在這種情況下不會改變任何內容。 – sberry 2014-10-30 16:24:46

+0

@sberry感謝「答案 - 重構」:-) – 2014-10-30 16:37:41

1

我認爲你應該乘以每個元組中的數字,但是num * num會給出正方形。我可以試試這個:

def product_of_tuples(nums_list): 
result = [] 
for tuple in nums_list: 
    s = 1 
    for item in tuple: 
     s *= item 
    result.append(s) 
return result