'Counter' 对象没有属性 'count'

'Counter' object has no attribute 'count'

有两个列表,我想检查有多少元素是重复的。假设列表一是 l1 = ['a', 'b', 'c', 'd', 'e'],列表二是 l2 = ['a', 'f', 'c', 'g']。由于 ac 在两个列表中,因此输出应该是 2 这意味着两个列表中有两个重复的元素。下面是我的代码,我想计算计数器中有多少 2。我不知道怎么算。

l1 = ['a', 'b', 'c', 'd', 'e']
l2 = ['a', 'f', 'c', 'g']
from collections import Counter
    c1 = Counter(l1)
    c2 = Counter(l2)
    sum = c1+c2
    z=sum.count(2)

你要的是set.intersection(如果每个列表都没有重复):

l1 = ['a', 'b', 'c', 'd', 'e']
l2 = ['a', 'f', 'c', 'g']

print(len(set(l1).intersection(l2)))

输出:

2

每次我们使用计数器时,它都会将列表转换为字典。所以它抛出错误。您可以简单地更改列表的数量和 运行 以下代码以获取重复值的确切数量。

# Duplicate elements in 2 lists
l1 = ['a', 'b', 'c', 'd', 'e']
l2 = ['a', 'f', 'c', 'g']# a,c are duplicate
from collections import Counter

c1 = Counter(l1)
c2 = Counter(l2)
sum = c1+c2
j = sum.values()
print(sum)
print(j)

v = 0
for i in j:
    if i>1:
        v = v+1

print("Duplicate in lists:", v)

输出:

Counter({'a': 2, 'c': 2, 'b': 1, 'd': 1, 'e': 1, 'f': 1, 'g': 1})
dict_values([2, 1, 2, 1, 1, 1, 1])
Duplicate in lists: 2