2017-09-14 38 views
1

如何在不使用'if'语句的情况下查找输入列表上的哪个位置? 我目前的代码如下。我想删除if语句,这样当一个品种被输入时,计算机输出“很棒的选择!”然后以尽可能紧凑的代码分别输出价格。我需要找到某个输入列表上的哪个值,并从另一个列表中打印相应的位置。(Python 3.5.2)如何查找列表中的哪个项目是我的输入?

dog_breed_list = ["daschund", "chihuahua", "French boxer", "Jack Russell", 
"poodle"] 

dog_price_list = [350, 640, 530, 400, 370] 

dog_choice = input("Welcome to the Pet Shop. \nWhich is your breed choice?") 

if dog_choice == dog_breed_list[0]: 
    print("Great choice! This breed costs £350.") 
elif dog_choice == dog_breed_list[1]: 
    print("Great choice! This breed costs £640.") 
elif dog_choice == dog_breed_list[2]: 
    print("Great choice! This breed costs £530.") 
elif dog_choice == dog_breed_list[3]: 
    print("Great choice! This breed costs £400.") 
+2

使用字典。 – Michael

+2

[查找包含Python的列表中的项目索引]可能的副本(https://stackoverflow.com/questions/176918/finding-the-index-of-an-item-given-a-list-含它合蟒) –

+0

在python加入@BilltheLizard文档字典API [字典API](https://docs.python.org/3.5/library/stdtypes.html#mapping-types-dict) – Andrei

回答

3

使用词典:

dog_breed_list = ["daschund", "chihuahua", "French boxer", 
        "Jack Russell", "poodle"] 

dog_price_list = [350, 640, 530, 400, 370] 

dictionary = {dog_breed_list[n]: dog_price_list[n] 
       for n in range(len(dog_breed_list))} 

dog_choice = input("Welcome to the Pet Shop. \nWhich is your breed choice? ") 

if dog_choice in dictionary: 
    print("Great choice! This breed costs £"+str(dictionary[dog_choice])+".") 
+0

使用字典进行投票是明显的选择,但即使保留这两个列表也没用 - 只需直接构建字典或至少从一个品种列表=>价格元组。 –

+0

这是一个很好的观点。我这样做是因为这意味着OP给出的代码的最小努力;-) – Michael

1

如果一定要使用这个列表,您可以使用.index()功能。

dog_breed_list = ["daschund", "chihuahua", "French boxer", 
        "Jack Russell", "poodle"] 

dog_price_list = [350, 640, 530, 400, 370] 

dog_choice = input("Welcome to the Pet Shop. \nWhich is your breed choice?") 

try: 
    dog_price = dog_price_list[dog_breed_list.index(dog_choice)] 
    print("Great choice! This breed costs £{}.".format(dog_price)) 

except ValueError: 
    print('That dog is not found in the list.') 

try - except块是因为.index()抛出一个值错误,如果它没有找到什么它寻找该列表。

相关问题