Reputation: 35
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
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
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
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
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