2015-02-12 44 views
1

我有一個列表/字典存儲與一些像這樣對應一個字:想不通這有什麼錯我的方法

MSG1  3027 
MEMORYSPACE 3036 
NEWLINE  3037 
NEG48  3038 

我的方法,如果用戶輸入單詞檢索號:

def retrieve_data(): 
    insert_data() 
    nb = input('Choose a label: ') 
    for j in data: 
     a=j[0] 
     b=j[1] 
     if a == nb: 
      print(b) 
     else: 
      print('Label not in list!') 

,所以我應該只得到3036但這是輸出我得到當我調用方法:

Choose a label: MEMORYSPACE 
Label not in list! 
3036 
Label not in list! 
Label not in list! 

任何想法,爲什麼它這樣做?謝謝

回答

1

那麼你遍歷所有的字典,只有每個項目一個匹配,因此它爲其他打印​​出Label not in list!。你想從別人刪除一個縮進級別和打印後突破(二)

def retrieve_data(): 
    insert_data() 
    nb = input('Choose a label: ') 
    for j in data: 
     a=j[0] 
     b=j[1] 
     if a == nb: 
      print(b) 
      break 
    else: 
     print('Label not in list!') 
4

您正在循環查看數據中的每個條目,因此它正在打印數據中的每個項目。這個問題是一個完美的解釋:

data = {'MSG1': 3027, 'MEMORYSPACE': 3036, 'NEWLINE': 3037, 'NEG48': 3038} 
nb = input('Choose a label: ') 
print(data.get(nb, 'Label not in list!')) 

(編輯按下面的評論,如果你仍然想它打印「不在列表中」)

+2

一點點的改進在這裏:'print(data.get(nb,'Label not in list!'))' – Eithos 2015-02-12 02:46:30

2

另一種方法做,這是

dic={"MSG1":3027,"MEMORYSPACE":3036,"NEWLINE":3037,"NEG48":3038} 


def retrieve_data(): 
    nb=raw_input("Choose a label: ") 

    if nb in dic.keys(): 
     print dic[nb] 
    else: 
     print "Label not in list!" 
0

它摻雜,因爲在你調用的foorloop的每cicle if/else語句將打印以太或以上的東西。只有一個圓圈你可以得到'正確的'答案。

有更好的方法做你想要什麼,但我會嘗試寫一個代碼CLOSé儘可能你:

def retrieve_data(): 
    found = False 
    insert_data() 
    nb = input('Choose a label: ') 
    for j in data: 
     a=j[0] 
     b=j[1] 
     if a == nb: 
      found = True 
      print(b) 
    if not found: 
     print('Label not in list!') 

或者

def retrieve_data(): 
    insert_data() 
    nb = input('Choose a label: ') 
    i = 0 
    while i < range(len(data)): 
     j = data[i] 
     a=j[0] 
     b=j[1] 
     if a == nb: 
      print(b) 
      break 
     i += 1 
else: 
    print('Label not in list!') 
相關問題