【问题标题】:Matching character lists of unequal length匹配长度不等的字符列表
【发布时间】:2019-10-14 04:37:38
【问题描述】:

我想匹配两个列表,其中一个列表较小,而另一个列表较大。如果两个列表之间发生匹配,则将匹配的元素放入新列表中相同索引处,而不是将其放入另一个索引。您可以从下面给出的代码中理解我的问题:

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']

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

【问题讨论】:

  • 长度较短的列表是否总是有 2 个字符串而较长的列表总是有 3 个字符串? list1 是否总是较小的列表?
  • 是的,它可以有两个字符串,第二个列表是三个字符串
  • 在下面查看我的答案

标签: python-3.x list loops


【解决方案1】:

使用嵌套循环遍历 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

【讨论】:

  • NJ 首先匹配 KNJ...您的问题没有解释为什么它应该跳过 KNJ
【解决方案2】:

鉴于问题没有指定任何约束,以更 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']

【讨论】:

    猜你喜欢
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    相关资源
    最近更新 更多