0

我对编程完全陌生,并且在 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
4

1 回答 1

1

使用 zip 遍历超过 1 个集合。(注意:此代码假定两个列表具有相同数量的项目,并且每个项目都是正确的 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]
于 2013-03-16T21:43:43.047 回答