【问题标题】:Python count two arrays of strings and integersPython计算两个字符串和整数数组
【发布时间】:2019-08-22 14:36:41
【问题描述】:

我有两个数组 X 和 Y,X 包含重复产品的标题,Y 包含已售出 X 数量的整数。

我用Counter统计了X中每个元素出现的次数,但是没有考虑到Y。

from collections import Counter
x = ['a','a','b','c','c','c','c','d','d','d','e','e']
y = [1, 5, 3, 1, 1, 1, 3, 5, 2, 1, 8, 1]

countX = Counter(x)

【问题讨论】:

  • 如何呢?它根本没有通过 y。
  • 我知道只是展示我尝试过的东西,如果我解决了问题就不会在这里

标签: python-3.x counter


【解决方案1】:

使用defaultdict:

from collections import defaultdict

x = ['a', 'a', 'b', 'c', 'c', 'c', 'c', 'd', 'd', 'd', 'e', 'e']
y = [1, 5, 3, 1, 1, 1, 3, 5, 2, 1, 8, 1]    

output = defaultdict(int)

for prod, count in zip(x, y):
    output[prod] += count

print(output)
# defaultdict(<class 'int'>, {'a': 6, 'b': 3, 'c': 6, 'd': 8, 'e': 9})

【讨论】:

  • 不确定,但我的赞成票将其设为 0,但非常感谢您的帮助!
猜你喜欢
  • 2016-08-13
  • 2016-10-21
  • 1970-01-01
  • 2014-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-18
  • 1970-01-01
相关资源
最近更新 更多