2017-08-20 96 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 |

您也可以使其成为负数 只需添加括号即可。是的。有乐趣和好运