2013-03-16 25 views
0

我完全不熟悉編程,並且閱讀了幾個Q &在Stackoverflow的一個關於兩個列表中的匹配字符串的問題,但沒有找到一個能幫助我處理這個確切任務的問題。比較和存儲兩個單詞列表中的匹配字母?

我必須列出,像這樣:

list1 = ["INTP", "ESFJ", "ENTJ"] 
list2 = ["ENTP", "ESFP", "ISTJ"] 

我想遍歷每個單詞的每個字母和存儲的所有比較,匹配字母的總數在列表和每一個面值的所有單詞的匹配,這樣的信件:

total_letters_compared = 12 
total_correct_matches = 8 
first_letter_pair_matches = 1 
second_letter_pair_matches = 2 
third_letter_pair_matches = 3 
fourth_letter_pair_matches = 2 

我無法弄清楚如何做到在某一指數的比較[I]在這兩個列表,以便我能以某種方式儲存在我的變量相匹配。到目前爲止我能夠想到的是:

total = 0 
total_letters_compared = 0 
total_correct_matches = 0 
first_letter_pair_matches = 0 
second_letter_pair_matches = 0 
third_letter_pair_matches = 0 
fourth_letter_pair_matches = 0 

for combination in list2: 
for letter in combination: 
    total_letters_compared = total_letters_compared + 1 
    if list2letter == list1.ltter: 
     total_correct_matches = total_correct_matches + 1 
     # here I´d like to keep track of which letter-pair is compared and 
        # add 1 to the correct variable or continue to the next letter-pair 

回答

1

使用zip來遍歷多個集合。 (注:此代碼假定兩個列表有相同數量的項目,每一個項目是一個正確的INTP配置文件)

matches = {0:0, 1:0, 2:0, 3:0} 

for item1, item2 in zip(list1, list2): 
    for i in xrange(4): 
     if item1[i]==item2[i]: 
     matches[i] += 1 

and you can extract data you want by: 

total_letters_compared = #length of a list * 4 
total_correct_matches = #sum(matches.values()) 
nth_letter_pair_matches = #matchs[n-1] 
+0

我得到一個錯誤信息: 在拉鍊物品1和ITEM2(列表1,列表2): ^ SyntaxError:無效語法 – mattiasostmar 2013-03-16 21:55:51

+0

@mattiasostmar編輯。對不起,這在Python中是相當無稽之談 – thkang 2013-03-16 21:56:24

相關問題