英文:
Python: Count element matches in arrays
问题
[3, 3]
,因为a的第一行和b有3列匹配,a的第二行和b有3列匹配。我想要统计a中每一行与b中的元素匹配的数量。每一列都是一个变量,所以顺序很重要。由于要处理大型数组,性能也很重要。
我尝试过[sum(x==y) for x,y in zip(a,b)]
,但这不正确。
英文:
a = [ ['Active', '1.0', '0.0', 'Business', 'London'], ['Active', '0.0', '0.0', 'Business', 'Scotland'] ]
b = ['Active', '0.0', '0.0', 'Retail', 'London']
Desired Output: [3, 3]
because 3 columns match for`a[row 0] and b, and 3 columns match for a[row 1] and b.
I want to count the number of element matches for each row in a compared with b. Each column is a variable so order matters. This is done for a big array so performance also matters.
I tried [sum(x==y) for x,y in zip(a,b)]
but this isn't right
答案1
得分: 1
代码中有一个问题:sum(x==y)
会对单个布尔值求和,而不是布尔值的列表。你应该使用嵌套列表来实现你的目标。以下是一种实现方法:
[sum([x==y for x,y in zip(a_element, b)]) for a_element in a]
输出结果是:[3, 3]
。
英文:
You got the idea, but there is a problem in the code: sum(x==y)
sums single boolean values instead of the list of bools. A nested list should be what you are looking for. Here is a way to do it:
[sum([x==y for x,y in zip(a_element, b)]) for a_element in a]
Output: [3, 3]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论