2017-04-21 163 views
0

我試圖讓我可以將每個成本乘以相應的銷售產品數量。例如,1.99 * 10,1.49 * 5等等。另外,我似乎無法弄清楚如何根據列表中的成本打印最昂貴或最便宜的產品的產品名稱。我試着將product_cost中的i與product_sold中的相應i相乘,但答案似乎沒有解決。有沒有人有任何想法如何解決這個問題?由於將兩個列表中的值相乘,然後將它們打印出來python

然而,用下面的代碼,

# product lists 
product_names = ["prime numbers", "multiplication tables", "mortgage calculator"] 
product_costs = [1.99, 1.49, 2.49] 
product_sold = [10, 5, 15] 

def report_product(): 
    total = 0 
    print("Most expensive product:", max(product_costs)) 
    print("Least expensive product:", min(product_costs)) 
    for i in range(len(product_costs)): 
     total += i * product_sold[i] 
    print("Total value of all products:", total) 

selection = "" 

while selection != "q": 
    selection = input("(s)earch, (l)ist, (a)dd, (r)emove, (u)pdate, r(e)port or (q)uit: ") 

    if selection == 'q': 
     break 
    elif selection == 's': 
     search_product() 
    elif selection == "l": 
     list_products() 
    elif selection == "a": 
     add_products() 
    elif selection == "r": 
     remove_products() 
    elif selection == "u": 
     update_products() 
    elif selection == "e": 
     report_product() 
    else: 
     print("Invalid option, try again") 

print("Thanks for looking at my programs!") 
+0

題外話:'如果選擇==「Q」:break'是多餘的,因爲while循環的條件是'而選擇=「q''使得環打破反正 – abccd

+0

u能顯示代碼search_product, list_products,remove_products,update_products,report_product函數.. ?? – shiva

回答

0

得到相應的指數相乘的一個新的數組,

product_costs = [1.99, 1.49, 2.49] 
product_sold = [10, 5, 15] 
product_mult = list(map(lambda x,y: x*y, product_costs,product_sold)) 

要找到它的名稱產品是最昂貴的,

index = product_costs.index(max(product_costs)) 
most_expensive = product_names[index] 
+1

代碼'[x * y for product_costs for y in product_sold]'產生所有九種可能的產品:'[19.9,9.95,29.85,14.9,7.45,22.35,24.900000000000002,12.450000000000001,37.35]'不是三個OP在尋找。 – cdlane

+0

謝謝,糾正! – Windmill

+0

代碼'index = product_mult.index(max(product_mult))'發現最賺錢的產品,不一定是最昂貴的產品。 – cdlane

1

雖然不一定是最優的,但您可以用最少的代碼usi得到答案NG zip()

def report_product(): 

    print('Most expensive product:', max(zip(product_costs, product_names))[1]) 

    print('Least expensive product:', min(zip(product_costs, product_names))[1]) 

    total_earned = sum(cost * sold for cost, sold in zip(product_costs, product_sold)) 

    print('Total earned from all products sold: ${:.2f}'.format(total_earned)) 

輸出

Most expensive product: mortgage calculator 
Least expensive product: multiplication tables 
Total earned from all products sold: $64.70 
0
>>> prod_m = [a*b for a,b in zip(product_costs, product_sold)] 
>>> prod_m 
[19.9, 7.45, 37.35] 
>>> product_names[product_costs.index(max(product_costs))] 
'mortgage calculator' 
>>> product_names[product_costs.index(min(product_costs))] 
'multiplication tables' 

您還可以使用numpy的兩個列表相乘。

>>> import numpy 
>>> list(numpy.array(product_costs)*numpy.array(product_sold)) 
[19.899999999999999, 7.4500000000000002, 37.350000000000001] 
相關問題