Python: 统计数组中匹配元素的数量

huangapple go评论62阅读模式
英文:

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]

huangapple
  • 本文由 发表于 2023年2月24日 01:13:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75548149.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定