python – 索引在2D列表中的位置,以从同一列表中获取子返回值
发布时间:2020-12-20 11:06:37 所属栏目:Python 来源:网络整理
导读:所以基本上我已经制作了两个不同的列表,并且它们的位置彼此相应. 用户输入项目名称.程序在预定义列表中搜索其索引,然后从第二个列表中提供其各自的值. 我想要的是第一个评论(2d列表)上的列表.是否有可能使用该列表,用户输入:’面包’. 程序获取其索引,然后
|
所以基本上我已经制作了两个不同的列表,并且它们的位置彼此相应.
用户输入项目名称.程序在预定义列表中搜索其索引,然后从第二个列表中提供其各自的值. 我想要的是第一个评论(2d列表)上的列表.是否有可能使用该列表,用户输入:’面包’. 程序获取其索引,然后返回值5. 如果您能提供代码或至少以正确的方式指导我. 谢谢. #super_market_prices=[['Bread',5],['Loaf',100],['Meat_Chicken',2.4],['Meat_Cow',450]]
'''
Program listing Super Market Prices
Search by name and get the price
'''
super_market_items=['Bread','Loaf','Meat_Chicken','Meat_Cow']
super_market_prices=[5,4,20,40]
item=str(input('Enter item name: '))
Final_item=item.capitalize() #Even if the user inputs lower_case
#the program Capitalizes first letter
try:
Place=super_market_items.index(Final_item)
print(super_market_prices[Place])
except ValueError:
print('Item not in list.')
解决方法
你不想要2D列表,你想要一本字典,幸运的是,从2D列表(每个子列表只有两个元素)到字典是非常简单的:
prices = [['Bread',450]]
d = dict(prices)
# {'Bread': 5,'Loaf': 100,'Meat_Chicken': 2.4,'Meat_Cow': 450}
现在你所要做的就是查询字典(O(1)lookup): >>> d['Bread'] 5 如果要启用错误检查: >>> d.get('Bread','Item not found')
5
>>> d.get('Toast','Item not found')
'Item not found'
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
