You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python内置函数统计嵌套列表中各元素的出现次数

Python嵌套列表元素出现次数统计方案

需求说明

给定嵌套结构的列表(列表元素仍为列表),需统计每个元素在所有子列表中的总出现次数,要求仅使用Python内置函数实现,最终按元素 - 出现次数的格式输出结果。

示例输入

data = [
    ['37772'],
    ['38119', '38120'],
    ['38103-2807', '38103-2897', '38103', '38104'],
    ['38138-3904', '38138'],
    ['37421'],
    ['37772'],
    ['37067'],
    ['37203'],
    ['38115'],
    ['38305'],
    ['37916'],
    ['37356'],
    ['38119']
]

预期输出示例

37772 - 2
38119 - 2
38120 - 1
38103-2807 - 1
38103-2897 - 1
38103 - 1
38104 - 1
38138-3904 - 1
38138 - 1
37421 - 1
37067 - 1
37203 - 1
38115 - 1
38305 - 1
37916 - 1
37356 - 1

实现代码

完全使用Python内置语法和函数,无需引入任何第三方库或标准库模块:

# 初始化计数字典
count_dict = {}

# 遍历所有元素统计次数
for sub_list in data:
    for item in sub_list:
        # 用字典get方法获取已有计数,默认值为0,累加后更新
        count_dict[item] = count_dict.get(item, 0) + 1

# 按要求格式输出
for item, count in count_dict.items():
    print(f"{item} - {count}")

简洁写法

也可以用生成器表达式扁平化嵌套列表,减少一层循环缩进:

count_dict = {}
for item in (item for sub_list in data for item in sub_list):
    count_dict[item] = count_dict.get(item, 0) + 1

for item, count in count_dict.items():
    print(f"{item} - {count}")

内容的提问来源于stack exchange,提问作者user3447653

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 10:45:03