使用字符串在列表中查找其整数值

时间:2018-10-24 17:21:46

标签: python python-3.x list

嘿,我想列出一个列表:(整数是它的花费金额)

Price=0
List=[('apple',1),('banana',2),('carrot',3)] 
Text=input('what do you want?')
Amount=int(input('how many do you want?'))
if Text=='apple':
    Price=List[int(0)]*Amount  
print(Price)

并能够使用其中一个找到另一个。这叫什么(/你怎么样 这样做),因为我尝试搜索它却一无所获,可能有 一直在寻找错误的东西,谢谢。

Price=0
List=[('apple',1),('banana',2),('carrot',3)]
Text=input('apple')
Amount=int(input('5'))
if Text=='apple':
    Price=1*5  
print(5)

我不知道这是否是你的意思@MayankPorwal

2 个答案:

答案 0 :(得分:2)

您可以尝试为此使用字典。您可以通过几种不同的方式创建字典,但是一种方法类似于{'apple': 1},其中dict键是项,值是价格。然后,您可以使用dict[key]根据用户输入访问价格。例如:

items = {'apple': 1, 'banana': 2, 'carrot': 3} 

item = input('what do you want?')
quantity = int(input('how many do you want?'))

if item in items:
    price = items[item] * quantity
    print(f'Item: {item} Quantity: {quantity} Price: {price}')
else:
    print('Item not found')

# OUTPUT for item input 'banana' and quantity input '2'
# Item: banana Quantity: 2 Price: 4

另外,由于list()是内置的python函数,因此请避免对变量使用“列表”之类的名称。

答案 1 :(得分:1)

字典是一个简单的解决方案。如果只想使用清单,则可以在单独的清单中跟踪商品和价格,因为商品和价格的顺序保持固定,然后使用输入商品的索引查找其关联价格。

items = ['apple', 'banana', 'carrot'] 
prices = [1, 2, 3]

item = input('what do you want?')
quantity = int(input('how many do you want?'))

if item in items:
    item_index = items.index(item)
    price = prices[item_index] * quantity
    print('Item: {} Quantity: {} Price: {}'.format(item, quantity, price))
else:
    print('Item not found')
相关问题