交叉匹配两个列表

时间:2012-10-20 00:28:19

标签: python

我有两个列表,我试图查看两个列表中元素中的子串之间是否存在匹配。

["Po2311tato","Pin2231eap","Orange2231edg","add22131dfes"]
["2311","233412","2231"]

如果元素中的任何子串与第二个列表匹配,例如“Po2311tato”将与“2311”匹配。然后我想把“Po2311tato”放在一个新列表中,其中匹配的第一个元素将放在新列表中。所以新的列表将是[“Po2311tato”,“Pin2231eap”,“Orange2231edg”]

3 个答案:

答案 0 :(得分:5)

您可以使用语法'substring' in string执行此操作:

a = ["Po2311tato","Pin2231eap","Orange2231edg","add22131dfes"]
b = ["2311","233412","2231"]

def has_substring(word):
    for substring in b:
        if substring in word:
            return True
    return False

print filter(has_substring, a)

希望这有帮助!

答案 1 :(得分:2)

通过使用列表理解,这可以比jobby的答案更简洁:

>>> list1 = ["Po2311tato","Pin2231eap","Orange2231edg","add22131dfes"]
>>> list2 = ["2311","233412","2231"]
>>> list3 = [string for string in list1 if any(substring in string for substring in list2)]
>>> list3
['Po2311tato', 'Pin2231eap', 'Orange2231edg']

这是否比jobby的版本更清晰/更优雅是一个品味问题!

答案 2 :(得分:0)

import re

list1 = ["Po2311tato","Pin2231eap","Orange2231edg","add22131dfes"]
list2 = ["2311","233412","2231"]
matchlist = []

for str1 in list1:
    for str2 in list2:
        if (re.search(str2, str1)):
            matchlist.append(str1)
            break

print matchlist