2016-12-12 9 views
-2

假設我的字典有如何拆分列表中的字符串並使用輸出與字典進行比較?

{'one': '1','two': '2', ..., 'hundred': '100'} 

和我的列表中包含

[['for 30']['for thirty']] 

我想在列表中的字符串分割爲:

[for],[30] and [for],[thirty] 

然後我想用'thirty'來與字典中的相應條目進行比較,並獲得'30'作爲輸出。

import csv 

reader = csv.reader(open('dict.csv', 'r')) 
d = {} 
for row in reader: 
    k, v = row 
    d[k] = v 

with open('test_term.csv', 'rb') as f: 
    reader = csv.reader(f) 
    your_list = list(reader) 
+0

'[ '30'] [ '三十']'='[ '30', '三十'] '? ''''='1','two'='2'........'hundred'='100'}'='{'one':'1','two':' 2'........'百':'100'}'? '[for],[30]'='['for',30]'? –

+0

你試圖做什麼比較?你需要以這種格式分割列表和字符串,還是隻想提取每個字符串的第二個單詞? – iled

+0

@safwan我已編輯您的問題,使其更具可讀性。請檢查它是否根據您的需要。然後嘗試通過回答我的問題來使它更加清晰。 – iled

回答

0

歡迎來到Python!你應該真的閱讀一些基本知識,比如如何聲明一個列表和一個字典。

我猜你試圖做的是:

# this is how you format a list 
pair_list = ['for 30', 'for thirty', 'for 1', 'for two'] 
# this is how you format a dict 
resolve_dict = {'one': '1', 'thirty': '30', 'hundred': '100'} 

# iterate the list two strings at a time 
for idx in xrange(len(pair_list)): 
    # example in comments 
    # pairs[idx] == 'for 30' 
    splitted = pair_list[idx].split(' ') 
    # splitted == ['for', '30'] 
    number = splitted[1] 
    # number == '30' 

    # pairs[idx + 1] == 'for thirty' 
    splitted = pair_list[idx + 1].split(' ') 
    # splitted == ['for', 'thirty'] 
    word = splitted[1] 
    # word == 'thirty' 

    # comparison 
    if resolve_dict[word] == number: 
     print 'hurray?' 
+0

它說pair_list沒有定義......我該如何解決它? – safwan

+0

我的不好。編輯。但真的,看代碼。你有一個引用變量的pair_list,但沒有聲明。 –

相關問題