How can I create a function in python that counts the coincidences between two lists?
本问题已经有最佳答案,请猛点这里访问。
如果在第一个列表中有一个元素重复出现,而在第二个列表中也出现了这个元素,这可能被视为1个巧合。
例子:
1 2 3 4 5 6 7 8 | >>> 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 |
我已经做到了:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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 |
这将返回一组重复的元素
1 | set(filter(set(lst1).__contains__, lst2)) |
加上len将计算其长度,这样重复元素的计数
1 | len(set(filter(set(lst1).__contains__, lst2))) |
基于
1 | set(lst1) & set(lst2) |