2017-09-14 27 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()拋出一個值錯誤,如果它沒有找到什麼它尋找該列表。

相關問題