2015-10-05 76 views
-1

我有元組至極的名單是:Python列表(查找與鍵值+檢查,如果存在的話)

TupleList = [("computer", "weird working machine"),("phone","talkerino"),("floor", "walk on")] 

而我想做的事就是讓打印出來的值,如果我有鑰匙

像:

x = raw_input("Word to lookup: ") # I insert "computer" 

,它應該打印出 「奇怪的工作機器」

TD LR:獲取與鍵的值

我需要修復的另一件事是,如果我嘗試追加元組添加一個新的單詞,說明已經存在的元組,它應該打印「已存在」否則它應該追加新單詞。類似這樣的:

if(word in tuple exist) 
    print "Already exist" 
else 
    TupleOrd.append(((raw_input("\n Word to insert: ").lower()),(raw_input("\n Description of word: ").lower()))) 
+1

你應該使用鍵值對的字典 –

回答

3

元組不是最大的鍵值查找數據類型。考慮使用字典來代替:

>>> TupleList = [("computer", "weird working machine"),("phone","talkerino"),("floor", "walk on")] 
>>> d = dict(TupleList) 
>>> d["computer"] 
'weird working machine' 

這也使得它更容易檢查的現有詞存在:

key = raw_input("Word to insert:").lower() 
if key in d: 
    print "Sorry, that word is already present" 
else: 
    d[key] = raw_input("Description of word:").lower() 

如果你絕對必須使用一個元組,你可以搜索鍵帶回路:

for key, value in TupleList: 
    if key == "computer": 
     print value 

並且類似地確定哪些鍵已經存在:

key_exists = False 
for key, value in TupleList: 
    if key == "computer": 
     key_exists = True 
if key_exists: 
    print "Sorry, that word is already present" 
else: 
    #todo: add key-value pair to tuple 
+0

我不太確定我可以把它變成字典,因爲「使命」是使它與1.列表2.元組3 。字典:D但是我可以使用它直到那時:D也許很難做到沒有字典但是ty! :) – Widdin

+0

像是有什麼辦法找到它與for循環,如果? (沒有字典) – Widdin

+0

是的,但並不容易。編輯。 – Kevin