【问题标题】:Compare and store matching letters in two lists of words?在两个单词列表中比较和存储匹配的字母?
【发布时间】:2013-03-16 21:37:04
【问题描述】:

我完全是编程新手,并且在 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

【问题讨论】:

    标签: python string python-2.7 comparison


    【解决方案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]
    

    【讨论】:

    • 我收到一条错误消息:对于 zip(list1, list2) 中的 item1 和 item2: ^ SyntaxError: invalid syntax
    • @mattiasostmar 已编辑。对不起,这在 python 中是很废话
    猜你喜欢
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 2017-09-30
    相关资源
    最近更新 更多