1

I have two lists where I am trying to see if there is any matches between substrings in elements in both lists.

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

If any substrings in an element matches the second list such as "Po2311tato" will match with "2311". Then I would want to put "Po2311tato" in a new list in which all elements of the first that match would be placed in the new list. So the new list would be ["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

This can be a little more concise than the jobby's answer by using a list comprehension:

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

Whether or not this is clearer / more elegant than jobby's version is a matter of taste!

于 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 に答える