代码之家  ›  专栏  ›  技术社区  ›  Ammar Sabir Cheema

长度不等的匹配字符表

  •  0
  • Ammar Sabir Cheema  · 技术社区  · 5 年前

    list1=['AF','KN','JN','NJ']
    list2=['KNJ','NJK','JNJ','INS','AFG']
    matchlist = []
    smaller_list_len = min(len(list1),len(list2))
    
    
    for ind in range(smaller_list_len):
        elem2 = list1[ind]
        elem1 = list2[ind][0:2] 
    
        if elem1 in list2:
           matchlist.append(list1[ind])
    

    获得的产量

    >>> matchlist
    ['KNJ', 'NJK', 'JNJ']
    

    期望输出

    >>> matchlist
    ['AFG', 'KNJ', 'JNJ', 'NJK']
    

    有没有办法得到想要的输出?

    0 回复  |  直到 5 年前
        1
  •  1
  •   Ruzihm aks786    5 年前

    使用嵌套循环遍历3字符列表。当该列表中的某个项包含2字符列表中的当前项时,将其追加并中断内部循环:

    list1=['AF','KN','JN','NJ']
    list2=['KNJ','NJK','JNJ','INS','AFG']
    matchlist = []
    smaller_list_len = min(len(list1),len(list2))
    
    
    for ind in range(smaller_list_len):
        for item in list2:
            if list1[ind] in item:
                matchlist.append(item)
                break
    
        2
  •  0
  •   Pynchia    5 年前

    如果问题没有指定任何约束条件,则使用列表理解,以更为python的方式:

    list1=['AF','KN','JN','NJ']
    list2=['KNJ','NJK','JNJ','INS','AFG']
    
    matchlist=[e2 for e1 in list1 for e2 in list2 if e2.startswith(e1)]
    

    生产

    ['AFG', 'KNJ', 'JNJ', 'NJK']