python-3.x - 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)
解决方案
使用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})
推荐阅读
- ansible - Ansible Synchronize 模块在测试时卡住
- python - 我不明白我的函数参数中的数组是什么形状
- php - 您如何跟踪继承方法的来源
- sql - 使用powershell——如何防止SQL访问同一条记录
- c# - ChromeDriver 未记录
- django - 初始化 django CheckboxSelectMultiple 并取消选中所有内容?
- c# - 是否可以通过 Messenger 控制发送到我的机器人的附件的大小?
- elasticsearch - ElasticSearch - 字段类型时间范围?
- bash - ssh上的for循环得到未绑定的变量错误
- python - 在 HTML (Flask) 中与 Python 并行迭代多个列表