user1675094
user1675094

Reputation: 35

python regular expression through each member of a list

From these two lists:

list_A = ["eyes", "clothes", "body" "etc"]
list_B = ["xxxx_eyes", "xxx_zzz", "xxxxx_bbbb_zzzz_clothes" ]

I want to populate a third list wit those objects from 2nd list, only if some part of his names matchs one of the names from the first list.

In the previous example, the third list has to be:

["xxxx_eyes", "xxxxx_bbbb_zzzz_clothes"]

Upvotes: 0

Views: 109

Answers (4)

user1446258
user1446258

Reputation:

Slowest but simplest would be:

list_A = ["eyes", "clothes", "body" "etc"]
list_B = ["xxxx_eyes", "xxx_zzz", "xxxxx_bbbb_zzzz_clothes" ]

list_C=[]
for _ in list_A:
    for __ in list_B:
        if _ in __:
            list_C.append(__)

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250951

In [1]: list_A = ["eyes", "clothes", "body" "etc"]

In [2]: list_B = ["xxxx_eyes", "xxx_zzz", "xxxxx_bbbb_zzzz_clothes" ]

In [7]: [x for x in list_B if any(y in list_A for y in x.split('_'))]
Out[7]: ['xxxx_eyes', 'xxxxx_bbbb_zzzz_clothes']

Upvotes: 1

jfs
jfs

Reputation: 414235

If you want to use regexs for this:

search = re.compile("|".join(map(re.escape, list_A))).search
result = filter(search, list_B)

Although Blender's answer might be enough in most cases.

Upvotes: 2

Blender
Blender

Reputation: 298176

If you want to use a list comprehension, this will work:

list_C = [word for word in list_B if any(test in word for test in list_A)]

Upvotes: 3

Related Questions