首页 > 解决方案 > Python计算两个字符串和整数数组

问题描述

我有两个数组 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)

标签: python-3.xcounter

解决方案


使用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})

推荐阅读