1

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

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

如果元素中的任何子字符串匹配第二个列表,例如“Po2311tato”,则将匹配“2311”。然后我想将“Po2311tato”放入一个新列表中,其中第一个匹配项的所有元素都将放入新列表中。所以新列表将是 ["Po2311tato","Pin2231eap","Orange2231edg"]

4

3 回答 3

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)

希望这可以帮助!

于 2012-10-20T00:35:58.350 回答
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 的版本更清晰/更优雅是一个品味问题!

于 2012-10-20T00:40:44.693 回答
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          
于 2012-10-20T00:37:16.370 回答