简体   繁体   English

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

[英]'Counter' object has no attribute 'count'

There are two lists and I want to check how many of elements are duplicate.有两个列表,我想检查有多少元素是重复的。 Assuming list one is l1 = ['a', 'b', 'c', 'd', 'e'] and list two is l2 = ['a', 'f', 'c', 'g'] .假设列表一是l1 = ['a', 'b', 'c', 'd', 'e']列表二是l2 = ['a', 'f', 'c', 'g'] . Since a and c are in both lists, therefore, the output should be 2 which means there are two elements that repeated in both lists.由于ac在两个列表中,因此,输出应该是2 ,这意味着在两个列表中都有两个重复的元素。 Below is my code and I want to count how many 2 are in counter.下面是我的代码,我想计算计数器中有多少2 I am not sure how to count that.我不知道如何计算。

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)

What you want is set.intersection (if there are no duplicates in each list):你想要的是set.intersection (如果每个列表中没有重复项):

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

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

Output:输出:

2

Every time we use a counter it converts the lists into dict.每次我们使用计数器时,它都会将列表转换为 dict。 So it is throwing the error.所以它抛出错误。 You can simply change the number of lists and run the following code to get the exact number of duplicate values.您可以简单地更改列表的数量并运行以下代码以获取重复值的确切数量。

# 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)

Output:输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM