计算另一个给定的整数列表的总出现次数

时间:2018-05-12 07:47:57

标签: python python-3.x counting

如何计算出同一整数的次数?

到目前为止我的代码:

def searchAlgorithm (target, array):
    i = 0 #iterating through elements of target list
    q = 0 #iterating through lists sublists via indexes
    while q < 4:
        x = 0 #counting number of matches
        for i in target:
            if i in array[q]:
                x += 1
            else:
               x == 0
        print(x)
        q += 1


a = [8, 12, 14, 26, 27, 28]
b = [[4, 12, 17, 26, 30, 45], [8, 12, 19, 24, 33, 47], [3, 10, 14, 31, 39, 41], [4, 12, 14, 26, 30, 45]]

searchAlgorithm(a, b)

这个输出是:

2
2
1
3

我想要实现的是计算次数&#39; 1&#39;,&#39; 2&#39; &#39; 3&#39;匹配发生。

我试过了:

v = 0
if searchAlgorithm(a, b) == 2:
    v += 1
print(v)

但这导致0

3 个答案:

答案 0 :(得分:1)

您可以使用集合的交集来查找两个列表中常见的元素。然后你可以得到集合的长度。以下是它的外观:

num_common_elements = (len(set(a).intersection(i)) for i in b)

然后,您可以遍历生成器num_common_elements以使用这些值。或者您可以将其转换为列表以查看结果:

print(list(num_common_elements))
[Out]: [2, 2, 1, 3]

如果您想自己实现交集功能,可以使用sum方法实现自己的版本。这相当于做len(set(x).intersection(set(y))

sum(i in y for i in x)

这是有效的,因为它会生成诸如[True, False, False, True, True]之类的值,表示第一个列表中的值出现在第二个列表中的位置。然后,sum方法将True s视为1,将False s视为0,从而为您提供交集的大小

答案 1 :(得分:0)

这是基于我从您的问题中理解的内容。可能你正在寻找这个:

from collections import Counter

def searchAlgorithm (target, array):
    i = 0 #iterating through elements of target list
    q = 0 #iterating through lists sublists via indexes
    lst = []
    while q < 4:
        x = 0 #counting number of matches
        for i in target:
            if i in array[q]:
                x += 1
            else:
               x == 0
        lst.append(x)
        q += 1
    print(Counter(lst))


a = [8, 12, 14, 26, 27, 28]
b = [[4, 12, 17, 26, 30, 45], [8, 12, 19, 24, 33, 47], [3, 10, 14, 31, 39, 41], [4, 12, 14, 26, 30, 45]]

searchAlgorithm(a, b)
# Counter({2: 2, 1: 1, 3: 1})

答案 2 :(得分:0)

感谢一些人提供的有用反馈,我已经提出了一个更简化的解决方案,完全符合我的要求。

通过在列表中存储匹配的results,我可以将列表从searchAlgorithm函数中返回,并简单地使用.count()来计算特定数字的所有匹配项在列表中。

def searchAlgorithm (target, array):
    i = 0 
    q = 0
    results = []
    while q < 4:
        x = 0 #counting number of matches
        for i in target:
            if i in array[q]:
                x += 1
            else:
               x == 0
        results.append(x)
        q += 1
    return results

a = [8, 12, 14, 26, 27, 28]
b = [[4, 12, 17, 26, 30, 45], [8, 12, 19, 24, 33, 47], [3, 10, 14, 31, 39, 41], [4, 12, 14, 26, 30, 45]]

searchAlgorithm(a, b)

d2 = (searchAlgorithm(winNum, lotto).count(2))