Python 使用不同的csv文件作为输入时出现KeyError
我有这个代码,它基本上是一个csv输入文件,打印出项目/项目的最低成本和餐厅id。但它在一个输入文件上抛出“KeyError”,但在另一个输入文件上却完美无瑕(两者风格相同)。有人能指出哪里错了吗?谢谢 一些重要注意事项:: 挑战::Python 使用不同的csv文件作为输入时出现KeyError,python,csv,Python,Csv,我有这个代码,它基本上是一个csv输入文件,打印出项目/项目的最低成本和餐厅id。但它在一个输入文件上抛出“KeyError”,但在另一个输入文件上却完美无瑕(两者风格相同)。有人能指出哪里错了吗?谢谢 一些重要注意事项:: 挑战:: 我的客户不想参观多家餐厅。因此,例如,如果他要求“extreme_fajita、jalapeno_poppers、extra_salsa”,那么代码应该打印商店6(在那里可以作为组合项目提供),而不是将用户需求分散在不同的餐厅(即使某些餐厅提供便宜的服务) 其次,
input.csv
1,4.00,tuna
1,8.00,tofu
2,5.00,tuna
2,6.50,tofu
3,4.00,chef_salad
3,8.00,steak__sandwich
4,5.00,steak__sandwich
4,2.50,wine_spritzer
5,4.00,extreme_fajita
5,8.00,fancy_eu_water
6,5.00,fancy_eu_water
6,6.00,extreme_fajita+jalapeno_poppers+extra_salsa
但我得到了这个错误:-
Traceback (most recent call last):
File "working.py", line 56, in <module>
solver(shop_text,['extra_salsa'])
File "working.py", line 42, in solver
(price, solution) = solve_one_shop(shop_info, required_items)
File "working.py", line 27, in solve_one_shop
for (price,combo) in shop[first_item]:
KeyError: 'extra_salsa'
==========输出===========
{'1': {'A': [[2.0, ['A']], [1.0, ['A', 'B']], [1.5, ['A', 'C']], [2.5, ['A', 'D']]], 'C': [[2.0, ['C']], [1.5, ['A', 'C']]], 'B': [[1.25, ['B']], [1.0, ['A', 'B']]], 'D': [[1.0, ['D']], [2.5, ['A', 'D']]]}, '2': {'A': [[3.0, ['A']]], 'C': [[1.2, ['C']]], 'B': [[1.0, ['B']]], 'D': [[1.25, ['D']]]}}
SHOP_ID=1
A,B(1.00) = 1.00
如果你的商店里没有额外的萨尔萨会发生什么
除了愤怒的喜欢莎莎舞的顾客,你的剧本不起作用,因为钥匙不存在
就像您正在检查项目
是否为空一样,您需要检查请求的项目是否实际在商店中:
def solve_one_shop(shop, items):
if len(items) == 0:
return [0.0, []]
all_possible = []
# first_item = items[0]
for item in items:
price,combo = shop.get(item, (0.0,[])) # This will return
# default values when
# the key doesn't exist
让我们从优化加载代码开始:
import csv
from collections import defaultdict
def build_shops(shop_file_name):
shops = defaultdict(list)
with open(shop_file_name, 'r') as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
id, cost, items = row
cost = float(cost)
items = items.split('+')
shops[id].append((cost, items,))
return shops
现在我们有了一个返回字典的函数,每个键都是表示成本的元组列表和项目列表
接下来,让我们优化解算器:
def solver(shops, required_items):
result_all_shops = []
shops_with_items = []
for i in required_items:
for shop, inventory in shops.iteritems():
for price, items in inventory:
if i in items:
shops_with_items.append((shop, price, i))
if not shops_with_items:
return [] # No shops contained the items
for i in required_items:
result_all_shops.append(min(filter(lambda x: x[2] == i, shops_with_items),
key=lambda x: x[1]))
return result_all_shops
最后,要加载所有内容:
if __name__ == '__main__':
shops = build_shops('input.csv')
items = ['extra_salsa','tofu']
result = solver(shops, items)
if not result:
print('Sorry, no shops contained {}'.format(','.join(items)))
else:
for shop, item, price in result:
print('Shop {} had the item {} for {}'.format(shop,price,item)))
谢谢你,伯翰。但6号餐厅有额外的萨尔萨。其次,如果查询solver(shop_text,['tuna']),我会得到相同的错误。第三,如果我仅用字母表替换项目(即“A”表示“金枪鱼”,“B”表示“豆腐”,等等),并且如果我使用解算器(shop_text,['A']),我会得到所需的准确结果。为什么在两个csv文件上会出现这种不同的行为?Burhan我编辑了我的文章,以包含正确的输出,以及我的代码所使用的文件。请看一下,帮我修一下。谢谢Burkhan但如果客户想要:——“极品法吉塔、墨西哥胡椒、额外的萨尔萨”,那么您的代码是给2家不同的餐厅5,6。但顾客只想在一家餐厅(如果所有餐厅都有)吃他要求的饭菜,在这种情况下,这家餐厅是6号餐厅。请看--我编辑了我的帖子并添加了“重要注意事项”,从现在起,您需要能够自己编辑此帖子:)
def solver(shops, required_items):
result_all_shops = []
shops_with_items = []
for i in required_items:
for shop, inventory in shops.iteritems():
for price, items in inventory:
if i in items:
shops_with_items.append((shop, price, i))
if not shops_with_items:
return [] # No shops contained the items
for i in required_items:
result_all_shops.append(min(filter(lambda x: x[2] == i, shops_with_items),
key=lambda x: x[1]))
return result_all_shops
if __name__ == '__main__':
shops = build_shops('input.csv')
items = ['extra_salsa','tofu']
result = solver(shops, items)
if not result:
print('Sorry, no shops contained {}'.format(','.join(items)))
else:
for shop, item, price in result:
print('Shop {} had the item {} for {}'.format(shop,price,item)))