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

Python新手求助:从嵌套列表提取数据生成指定结构字典

解决Python嵌套列表生成星期出生数统计字典的问题

Hey there! As a fellow Python enthusiast who's fumbled through nested data structures early on, let's break down how to get that weekday birth count dictionary you need.

思路梳理

Your nested list has a header row first, followed by data rows where:

  • The 4th element (index 3) is day_of_week (as a string, values 1-7)
  • The 5th element (index 4) is births (also a string, the number of births that day)

We need to loop through each data row, convert those strings to integers, and accumulate the total births for each weekday.

方法1:基础循环(适合新手理解)

This approach is straightforward and great for learning how the aggregation works under the hood:

# 你的原始嵌套列表
birth_data = [['year', 'month', 'date_of_month', 'day_of_week', 'births'], 
              ['1994', '1', '1', '6', '8096'], 
              ['1994', '1', '2', '7', '7772'], 
              ['1994', '1', '3', '1', '10142'],
              # 其他数据行...
             ]

# 初始化结果字典,确保1-7所有星期键都存在,初始值为0
days_counts = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0}

# 跳过表头行,遍历所有数据行
for row in birth_data[1:]:
    # 把字符串类型的星期和出生数转为整数
    weekday = int(row[3])
    num_births = int(row[4])
    # 累加对应星期的出生总数
    days_counts[weekday] += num_births

# 输出结果
print(days_counts)

方法2:用collections.defaultdict简化代码

If you want a more concise way (and don't want to manually initialize all keys), defaultdict from the collections module is perfect—it automatically sets missing keys to 0:

from collections import defaultdict

birth_data = [['year', 'month', 'date_of_month', 'day_of_week', 'births'], 
              ['1994', '1', '1', '6', '8096'], 
              ['1994', '1', '2', '7', '7772'], 
              ['1994', '1', '3', '1', '10142'],
              # 其他数据行...
             ]

# 初始化默认值为0的字典
days_counts = defaultdict(int)

for row in birth_data[1:]:
    weekday = int(row[3])
    num_births = int(row[4])
    days_counts[weekday] += num_births

# 可选:确保字典包含1-7所有键(即使某个星期没有出生数据)
days_counts = {day: days_counts.get(day, 0) for day in range(1, 8)}

print(days_counts)

关键提示

  • 类型转换很重要: The original data stores numbers as strings, so we have to use int() to convert them—otherwise, you'd be concatenating strings instead of adding numbers!
  • 跳过表头: We use birth_data[1:] to start looping from the second row, since the first row is just column names.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:26:51