如果在第一个列表中重复一个元素,并且在第二个列表中也会出现此元素,则可能会将其计为1个重合
示例:
>>> comptaCoincidencies(['verd', 'groc', 'blau', 'vermell'], ['marro', 'blau', 'blanc', 'negre'])
0
>>> comptaCoincidencies(['verd', 'groc', 'blau', 'vermell'], ['blanc', 'negre', 'verd', 'groc'])
2
>>> comptaCoincidencies(['verd', 'groc', 'blau', 'vermell'], ['vermell', 'blau', 'groc', 'verd'])
4
>>> comptaCoincidencies(['verd', 'verd', 'verd', 'verd'], ['vermell', 'blau', 'groc', 'verd'])
1
我做到了:
def comptaCoincidencies(l1, l2):
"""
Donades dues llistes, retorna el nombre d'elements coincidents entre le llistes
>>> comptaCoincidencies(["verd", "verd"], ["blau", "blau"])
0
>>> comptaCoincidencies(["verd", "vermell"], ["verd", "blau"])
1
>>> comptaCoincidencies(["verd", "blau"], ["blau", "verd"])
2
"""
comptador = 0
for i in range(0, len(l1)):
if l1[i] in l2:
comptador = comptador + 1
return comptador
答案 0 :(得分:1)
这将返回一组重复的元素
set(filter(set(lst1).__contains__, lst2))
并添加len将计算其长度,以便重复元素的计数
len(set(filter(set(lst1).__contains__, lst2)))
根据@Willem Van Onsem
评论
set(lst1) & set(lst2)