2015-10-18 33 views
0

我必須使用一個用元組填充的列表來創建一個字典。每個元組應該是一對,例如(word,description_of_said_word)。 到目前爲止,我有這樣的:試圖在python中創建一個查找函數

banana = ("banana", "a yellow fruit") 
orange = ("orange", "a orange fruit") 
apple = ("apple", "a green fruit") 
my_list = [banana, orange, apple] 

def lookup(): 
    word = raw_input("Word to lookup: ") 
    print ("\n") 
    n = my_list.index(word) 
    x = my_list[n][0] 
    y = my_list[n][1] 
    if word == x: 
     print x, ":", y, "\n" 
    else: 
     print("That word does not exist in the dictionary") 
lookup() 

當我在寫的香蕉,我得到一個錯誤說,「ValueError異常:‘香蕉’是不在列表中」。我究竟做錯了什麼?

回答

1

一種方式做,這是遍歷元組的列表,並輸入單詞比較在每個元組的第一個項目。如果匹配,則打印並返回。如果它在整個列表中找不到匹配項,請讓用戶知道該詞不存在。

banana = ("banana", "a yellow fruit") 
orange = ("orange", "a orange fruit") 
apple = ("apple", "a green fruit") 
my_list = [banana, orange, apple] 

def lookup(): 
    word = raw_input("Word to lookup: ") 
    print ("\n") 
    for fruit in my_list: 
     if fruit[0] == word: 
      print fruit[0], ":", fruit[1], "\n" 
      return 
    print("That word does not exist in the dictionary") 
lookup() 
+0

如何讓用戶知道而不讓它穿過循環? –

+0

那麼,如果它在整個循環中運行之前找到匹配項,它將在找到並退出時立即打印出來。除非你運行整個循環(或者使用不同的結構,如字典,而不是元組列表),否則無法知道該單詞是否不在字典中。 – Jon

+0

我添加了一個else語句,在循環中打印出「該詞在詞典中不存在」。如果我之後休息一下好嗎?所以它不會打印出相同的消息n次? –

1

"banana"不在my_list("banana","a yellow fruit")是。這些是不同的對象。

如果改用my_dict = dict([banana,orange,apple])你會得到一個實際的字典中"banana"是一個關鍵和my_dict["banana"]會給你"a yellow fruit"

更多在這裏閱讀:https://docs.python.org/2/library/stdtypes.html#mapping-types-dict

+0

噢好吧,這很合理。那麼我如何檢查元組中的第一個元素呢? :) –

+0

事情是我不允許使用字典,只有一個列表填充元組:/ –

+0

然後有沒有標準的功能,它會做到AFAIK。使用for循環遍歷my_list,並手動查找索引。 –