2012-02-16 21 views
0
Table = u'''A,This is A 
B,This is B 
C,This is C 
D,This is D 
E,This is E 
F,This is F 
G,This is G 
H,This is H 
I,This is I 
J,This is J''' 

SearchValue = u'''A 
B 
C 
D 
Bang 
F 
Bang 
G 
H''' 

Table = Table.splitlines() 
LineText = {} 
for targetLineText in Table: 
    LineText[targetLineText.split(',')[0]] = targetLineText.split(',')[1] 

SearchValue = SearchValue.splitlines() 
for targetValue in SearchValue: 
    print LineText[targetValue] if targetValue in LineText else 'Error:' + targetValue 

這段代碼是幹什麼獲取字典值的表現...... 它找到值列表從「表」字典的鍵名爲「SearchValue」最好在python

我檢查鍵存在以下代碼..

targetValue in LineText 

我想要做的是在關鍵值存在檢查的同時獲取值。因爲我認爲這表現更好。

回答

2

你應該看看到dict.get方法:

SearchValue = SearchValue.splitlines() 
for targetValue in SearchValue: 
    print LineText.get(targetValue, 'Error:' + targetValue) 
+0

這正是我一直在尋找。謝謝。 – Nigiri 2012-02-16 11:15:59

1

我重新格式化根據the python style guide你的代碼,並增加了一些優化:

table = u'''A,This is A 
B,This is B 
C,This is C 
D,This is D 
E,This is E 
F,This is F 
G,This is G 
H,This is H 
I,This is I 
J,This is J''' 

search_value = u'''A 
B 
C 
D 
Bang 
F 
Bang 
G 
H''' 

line_text = dict(line.split(",") for line in table.splitlines()) 

for target_value in search_value.splitlines(): 
    print line_text.get(target_value, "Error: {0}".format(target_value)) 
+0

很好!非常感謝!!我必須知道Python風格 – Nigiri 2012-02-16 11:20:42

相關問題