2017-08-20 93 views
-1

我需要一些幫助來處理我的代碼。我最近開始從朋友那裏學習Python。通常,如果我遇到問題,他會告訴我該怎麼做,但他休假幾周,所以他不能幫忙。我需要創建一個價格比較工具來比較產品的價格。我可以完成大部分代碼,我只需要幫助我們如何從列表中獲取內容。我可以收集所有信息並將其放入列表中,但我不確定如何再次將它取出。我需要它顯示所有輸入產品的平均單價,最便宜的整體產品,最昂貴的整體產品以及用戶設置的預算中最便宜單價的建議。我不知道如何從列表中收集此信息。任何幫助,將不勝感激。這是我的代碼到目前爲止:(我已經遺漏了功能)從列表中獲取信息

keep_going = "" 
while keep_going == "": 

    sum_table = [] 
    count = 0 
    unit_type = "" 

    print("Welcome to the price comparison tool!") 
    print() 
    how_much = num_check("How much money do you have to spend? $", float, 1, 100) 

    get_prod = True 
    while get_prod: 

     if count < 1: 
      p_name = len_check("What is the name of the first product? ") 
     elif 0 < count: 
      p_name = len_check("Please enter another product, or type XXX to bring up summary ") 
      if p_name.lower() == "xxx": 
       break 

     unit = num_check("Is the product in g/ml or kg/L? (enter 1 for g/ml or 2 for kg/l) ", int, 1, 2) 
     if unit == 1: 
      unit_type = "grams/millilitres" 
     elif unit == 2: 
      unit_type = "kilograms/litres" 

     p_mass = num_check("What is the mass of '{}' in {}? " .format(p_name, unit_type), float, 1, 1000) 
     if unit == 2: 
      p_mass = p_mass*1000 
     p_price = num_check("What is the price of '{}' in dollars? $" .format(p_name), float, 0.1, 100) 
     p_average = p_price/(p_mass/1000) 

     row = [p_name, p_mass, p_price, p_average] 
     sum_table.append(row) 
     count += 1 

    for i in sum_table: 
     if i[2] > how_much: 
      sum_table.remove(i) 

    print() 
    print("--- Product Summary ---") 
    print("All items over-budget have been removed! ") 
    print("Name\tMass in g/ml\tPrice\tUnit price per kg") 
    for i in sum_table: 
     print(i) 

    print() 
    keep_going = input("Press <enter> to go again or any other key to quit") 
    print() 
+0

考慮添加註釋你的代碼解釋自己在做什麼,或者你有 – Cuber

+0

什麼問題還有,什麼是'len_check()'和'num_check()'? –

+1

有很多內置的功能(最小,最大,總和等),它們可以完成你想要實現的功能,只需將它們放到谷歌地圖上,你就會發現很多信息。 – coder

回答

1

在你顯示它的方式,不同的項目,你可以拉出每個項目的行。

例如:

>>> row = [1,2,3,4,5] 
>>> a,b,c,d,e = row 
>>> print a,b,c,d,e 
1 2 3 4 5 

在排因此循環並使用p_name, p_mass, p_price, p_average = row[i]

查閱(作爲一個例子),設置最大 - 對索引作爲表示最大價格的行的索引。和max-p作爲實際最大價格值。您可以對每個想要跟蹤的值進行類似的計算,並且可以構建平均值。一旦你完成循環,你將擁有所有你需要的值。

if max-p < p_price: 
    max-p = p_price 
    max-p-index = i 

您可以通過排在這個循環中得到最便宜的價格,單位價格,平均等以同樣的方式已經取下了過高的行之後。

0

您可以通過添加括號和數字從數組中提取信息。 因此,讓我們首先定義數組:

>>> list = [1,3,5,7,9] 

然後,讓我們進入這個打印整個列表:

>>> print (list) 

以下結果:

[1, 3, 5, 7, 9] 

現在我們所說的個別數字這樣做。我們在最後添加一對括號。在括號中,你輸入一個號碼來呼叫號碼。您輸入到括號中的數字應該是列表中的一個數字。例如:

>>> list[0] 
    1 

    >>>list[1] 
    3 

它打印出你放多少,但在順序。零是起始數字。這就像一個表:

列表1 | 3 | 5 | 7 | 9

致電0 | 1 | 2 | 3 | 4 或... -4 | -3 | -2 | -1 |

您也可以使其成爲負數 只需添加括號即可。是的。有樂趣和好運