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.
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