0

Now I have two 2D arrays, I want to compare

['A','B','E','G', 'T'] & ['A','C','E','N','M']
['a','f','c','h','u'] & ['a','b','c','y','l']

and calculate the same elements.

aaa = [['A','B','E','G','T'],['a','f','c','h','u']]
bbb = [['A','C','E','N','M'],['a','b','c','y','l']]

So in this example, the output is 2+2

I know how to do if it's a 1D array, but don't know how to do this with 2D arrays. Many thanks.

Cecilia
  • 309
  • 2
  • 12

2 Answers2

2

You could use zip() builtin method to pair elements:

aaa = [['A','B','E','G','T'],['a','f','c','h','u']]
bbb = [['A','C','E','N','M'],['a','b','c','y','l']]

c = sum(ii[0] == ii[1] for i in zip(aaa, bbb) for ii in zip(*i))
print(c)

Prints:

4

EDIT: If you don't care about order of elements, you can use sets:

aaa = [['A','E','C','G','T'], ['a','f','c','h','u']]
bbb = [['A','C','E','N','M'], ['a','b','c','y','l']]

c = sum(len(set(i1) & set(i2)) for i1, i2 in zip(aaa, bbb))
print(c)

Prints (Common elements in first array 'A', 'E', 'C' and in second array 'a', 'c'):

5
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • Hi Andrej, what if I don't care about the order of the elements, just sum the mutual elements? For instance, aaa = [['A','E','C','G','T'], bbb = [['A','C','E','N','M'], there are three mutual elements, but the output is not 3 – Cecilia Jul 28 '19 at 09:14
  • @Cecilia See my updated answer – Andrej Kesely Jul 28 '19 at 11:32
0

You can use itertools.chain to flatten lists of lists, and use zip to pair elements of those flattened lists.

from itertools import chain

aaa = [['A','B','E','G','T'], ['a','f','c','h','u']]
bbb = [['A','C','E','N','M'], ['a','b','c','y','l']]

c = sum(a == b for a, b in zip(chain(*aaa), chain(*bbb)))

EDIT: With this method, you might want to be careful that aaa and bbb have the same dimensions because the following code will produce the same result as above.

from itertools import chain

aaa = [['A','B','E','G'], ['T','a','f','c','h','u']]
bbb = [['A','C','E','N','M','a'], ['b','c','y','l']]

c = sum(a == b for a, b in zip(chain(*aaa), chain(*bbb)))
brentertainer
  • 2,118
  • 1
  • 6
  • 15