如何在python中创建一个计算两个列表之间重合的函数?

时间:2018-01-04 17:13:18

标签: python

如果在第一个列表中重复一个元素,并且在第二个列表中也会出现此元素,则可能会将其计为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

1 个答案:

答案 0 :(得分:1)

这将返回一组重复的元素

set(filter(set(lst1).__contains__, lst2))

并添加len将计算其长度,以便重复元素的计数

len(set(filter(set(lst1).__contains__, lst2)))

根据@Willem Van Onsem评论

进行更新
set(lst1) & set(lst2)