Partial match between two arrays in python

I have two arrays:

a1 = ['a', 'b', 'c', 'd']
a2 = ['a_111', 'd_111']

how can I navigate a full array and do a partial match to find the difference

['b', 'c']

and add 'b_111', 'c_111'in an array a2?

Is there any specific way to do this in python? Thank!

+3
source share
1 answer

You can use a list comprehension / list.extendand all:

>>> a2 += [x + '_111' for x in a1 if all(x not in y for y in a2)]
>>> a2
['a_111', 'd_111', 'b_111', 'c_111']

or

>>> a2.extend(x + '_111' for x in a1 if all(x not in y for y in a2))

If you want ['b', 'c'], then you can break the above code into two stages:

>>> partial =  [x for x in a1 if all(x not in y for y in a2)]
>>> partial
['b', 'c']
>>> a2 += [x + '_111' for x in partial]
>>> a2
['a_111', 'd_111', 'b_111', 'c_111']
+2
source

All Articles