如何找到两个列表的共同元素?

Mar*_*ria 2 python python-3.x

我试图使用 python 3 查找两个列表的公共元素,并有一个新列表,其中公共元素仅出现一次。这是我到目前为止所拥有的:

lengtha = len(lista);
lengthb = len(listb);

identical = [];
checker = 0;

for i in range (0, lengtha-1):
    for j in range (0, lengthb-1):
        if lista[i] == listb[j]:
            length = len(identical);
            for h in range (0, length-1):
                if lista[i] == identical[h]:
                checker = 1;
            if checker == 0:
                identical.append(list[i]);
            checker = 0;
Run Code Online (Sandbox Code Playgroud)

当我尝试使用列表时

lista = ['hello', 'cat', 'dog', 'dog']
listb = ['hello', 'cat', 'cat', 'mouse', 'whale', 'whale', 'elephant', 'whale', 'elephant', 'dog', 'dog']
Run Code Online (Sandbox Code Playgroud)

结果是['hello','cat','cat','dog']。我不明白为什么'cat'出现两次而其他复制的动物却没有。

Aul*_*hal 5

使用sets,它就像一个列表,但只能保存唯一的项目:

set(lista).intersection(listb)
Run Code Online (Sandbox Code Playgroud)