在Python中遍历多个索引

2024-04-25 20:39:52 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个交叉从reddit(指向这个方向由我的SO)任何帮助将不胜感激。你知道吗

我正在做作业,我有几个关于阅读多个指数的问题。我想要的结果是建立一个相互反馈的列表。在这种情况下,它是建立一个水果清单,然后询问水果有多贵,然后询问一个客户有多少,然后再显示每个客户的总数,为每个客户循环,直到你点击完成。这是用python2.7编写编程类的简介

正确的输出如下所示:

Enter a fruit name (or done): Mango
Enter a fruit name (or done): Strawberry
Enter a fruit name (or done): Kiwi
Enter a fruit name (or done): done

Enter the price for Mango: 2.54
Enter the price for Strawberry: 0.23
Enter the price for Kiwi: .75

Enter customer name (or done): Bob
Mango($2.54) Quantity: 3
Strawberry($0.23) Quantity: 10
Kiwi($0.75) Quantity: 2

Bob's total purchase is $11.42

Enter customer name (or done): Lisa
Mango($2.54) Quantity: 10
Strawberry($0.23) Quantity: 40
Kiwi($0.75) Quantity: 20

到目前为止,我已经建立了一个程序,可以(或多或少地)建立一个水果列表,询问价格,并计算总数,但我不太清楚如何整合一个最终的“客户列表” 我的代码如下:

flist = []
print "Enter a fruit name (or done): " ,
fruit_name = raw_input()
while fruit_name != 'done':
  flist.append(fruit_name)
  print "Enter a fruit name (or done): ",
  fruit_name = raw_input()

print " "   

price_list = [] 
for p in flist:
  print "Enter the price for " + p + ":",
  price = float(raw_input())
  price_list.append(price)

qlist = []
for q in range(len(flist)):
  print "How many " + str(flist[q]) + ' (' + '$' +     str(price_list[q]) + ')' ":",   
  quantity = raw_input()
  qlist.append(quantity)

total = 0
for i in range(len(flist)):
  total += float(price_list[q]) * int(qlist[q])
print "Your total purchase is $ " + str(total) 

我不知道如何从这里继续下去。任何帮助都将不胜感激。事先非常感谢。你知道吗


Tags: ornamefor客户pricequantitytotalprint
1条回答
网友
1楼 · 发布于 2024-04-25 20:39:52

好吧,以下是一些让你不用做作业就可以开始的想法:

  • 如果您的最终目标是打印出一个客户列表,其中包含他们拥有的水果和客户总数,那么您可能应该将所有这些数据存储在一起,而不是存储在单独的列表中。因此,可以考虑使用类似于字典的方法,其中键是客户名称,值是包含每个水果的编号和其他相关信息的子字典。如果您将所有这些数据存储在一起,那么打印单个客户信息就容易多了

  • 可能你要做的第一件事就是询问客户的名字。然后您可以使用它来设置字典中的第一个键。

  • 当您循环遍历水果名称时,您可以使用这些名称作为该客户的附加键,其中值是每个水果的编号

  • 您将需要另一个dict来保存每个水果的价格

一旦你有了这种类型的结构,你就可以像这样把所有的东西都打印出来:

#Get these values with loops like you're currently doing
customerDict = {"bob": {"orange": 3,"apple": 1},
                "alice": {"orange": 2,"apple": 1}}

priceDict = {"orange": 1.2, "apple": 1.1}

#get this from user input
customerName = "bob" 

total = 0

print customerName
for k,v in customerDict[customerName].items():
    print "%s (%s), Quantity: %s" % (k, str(priceDict[k]), str(v))
    total += (priceDict[k] * v)

print "Total: " + str(total)

它将返回类似于:

bob
orange (1.2), Quantity: 3
apple (1.1), Quantity: 1
Total: 4.7

相关问题 更多 >