我有2D数组,我想比较
['A','E','C','G', 'T'] & ['A','C','E','N','M']
['a','f','b','c','u'] & ['a','b','c','y','l']
并计算相同的元素(无论元素的顺序如何)。
aaa = [['A','E','C','G','T'],['a','f','b','c','u']]
bbb = [['A','C','E','N','M'],['a','b','c','y','l']]
因此在此示例中,输出为6(3+3)
我尝试过:
c = sum(ii[0] == ii[1] for i in zip(aaa, bbb) for ii in zip(*i))
print(c)
但输出为2 (1+1)
答案 0 :(得分:0)
下面
set1 = set(['A','E','C','G', 'T'])
set2 = set(['A','C','E','N','M'])
common_elements = set1.intersection(set2)
print(common_elements)
print('Number of common elements is: {}'.format(len(common_elements)))
输出
{'A', 'C', 'E'}
Number of common elements is: 3
答案 1 :(得分:0)
您可以使用:
sum(len(set(ai) & set(bi)) for ai, bi in zip(aaa, bbb))
这会将基于元素的子列表转换为集合,并计算相交中的元素数量。
例如:
>>> sum(len(set(ai) & set(bi)) for ai, bi in zip(aaa, bbb))
6