【发布时间】:2017-07-12 18:02:55
【问题描述】:
我编写了一个代码,它读取作为输入给出的产品并给出产品价格的输出
data.csv 文件
1, 4.00, teddy_bear
1, 8.00, baby_powder
2, 5.00, teddy_bear
2, 6.50, baby_powder
3, 4.00, pampers_diapers
3, 8.00, johnson_wipes
4, 5.00, johnson_wipes
4, 2.50, cotton_buds
5, 4.00, bath_towel
5, 8.00, scissor
6, 5.00, scissor
6, 6.00, bath_towel, cotton_balls, powder_puff
python 代码
import csv
with open('data.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
usrid = []
price = []
product = []
for row in readCSV:
usrid.append(row[0])
price.append(row[1])
product.append(row[2])
askProduct = raw_input('What Product do you wish to know the price of?:')
abc = product.index(askProduct)
thePrice = price[abc]
print ('the price of product',askProduct, 'is', thePrice)
产生错误
Traceback (most recent call last):
File "C:/Users/Desktop/program.py", line 15, in <module>
abc = product.index(askProduct)
ValueError: 'teddy_bear' is not in list
需要以下输出
Program Input
program data.csv teddy_bear baby_powder
Expected Output
=> 2(userid), 11.5(addition of two products)
【问题讨论】:
-
如果您打印出您的清单,您会注意到产品名称前面有空格。这就是您无法正确搜索它们的原因
标签: python python-2.7 csv