Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

partial match between two arrays in python

I have two arrays:

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

how can I loop thorough array and do a partial match to find the difference is

['b', 'c']

and add 'b_111', 'c_111' to array a2?

Is there any particular way to do it in python? Thanks!

like image 638
amstree Avatar asked Dec 01 '25 03:12

amstree


1 Answers

You can use a list comprehension/list.extend and 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'] as well, then you can break the above code into two steps:

>>> 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']
like image 104
Ashwini Chaudhary Avatar answered Dec 02 '25 18:12

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!