如何基于二维数组中子数组的第二个值统计各年份水果数量?
实现二维数组年份水果数量统计
Python 实现
基础字典遍历法
data = [['apples', 2020], ['pears', 2020], ['apples', 2021], ['melons', 2020], ['peaches', 2021], ['pears', 2019]] year_count = {} for _, year in data: # 若年份已存在则加1,不存在则初始化为1 year_count[year] = year_count.get(year, 0) + 1 print(year_count) # 输出: {2020: 3, 2021: 2, 2019: 1}
使用collections.defaultdict简化代码
from collections import defaultdict data = [['apples', 2020], ['pears', 2020], ['apples', 2021], ['melons', 2020], ['peaches', 2021], ['pears', 2019]] year_count = defaultdict(int) for _, year in data: year_count[year] += 1 # 转换为普通字典输出 print(dict(year_count)) # 输出: {2020: 3, 2021: 2, 2019: 1}
JavaScript 实现
遍历统计
const data = [['apples', 2020], ['pears', 2020], ['apples', 2021], ['melons', 2020], ['peaches', 2021], ['pears', 2019]]; const yearCount = {}; data.forEach(([_, year]) => { yearCount[year] = (yearCount[year] || 0) + 1; }); console.log(yearCount); // 输出: {2019: 1, 2020: 3, 2021: 2}
使用reduce方法
const data = [['apples', 2020], ['pears', 2020], ['apples', 2021], ['melons', 2020], ['peaches', 2021], ['pears', 2019]]; const yearCount = data.reduce((acc, [_, year]) => { acc[year] = (acc[year] || 0) + 1; return acc; }, {}); console.log(yearCount); // 输出: {2019: 1, 2020: 3, 2021: 2}
内容的提问来源于stack exchange,提问作者unnamed_road
相关产品推荐
相关产品推荐

