首页 > 解决方案 > 将嵌套列表中的日期字符串拆分为按月对列表进行分组 - Python

问题描述

这是一个家庭作业。我不允许使用库等。目的是学习和理解 Python 中的嵌套列表、循环和条件过滤。

我有一个嵌套的数据列表,下面是一个简短的摘录。它有 200 行长。

patients = [ ['Milos', 'Jones', '15/01/20', 'male', 'smoker', '210'],
             ['Delia', 'Chan', '15/03/20', 'female', 'non-smoker', '170'],
             ['Denise', 'Ross', '13/02/20', 'female', 'non-smoker', '150'] ]

我需要能够按性别和月份过滤列表。将每个列表中的 [5] 元素转换为准备好的整数。

要按性别过滤,我编写了以下代码:

female_patients = []
for solo_patient in patients:
    if solo_patient[3] == 'female':
        female_patients.append(solo_patient)

我已使用以下方法将元素转换为整数:

for solo_patient in patients:
    solo_patient[5] = int(solo_patient[5])
      

工作和输出我需要的东西。

但是,我正在尝试将数据拆分为字符串并转换为整数,以便按月过滤。我使用了与上面类似的逻辑,但我无法使其正常工作。

for solo_patient in patients:
patients[2] = [solo_patient[2].split('/')

这给了我一个错误“IndexError:列表索引超出范围”

如果我使用代码:

for solo_patient in patients:
patients = [solo_patient[2].split('/')

它将日期拆分为“MM”、“DD”、“YY”,但我丢失了其他数据。

当我将它拆分时,我需要将日期字符串转换为整数,然后使用 range(1,13) 的循环遍历并按月分组。然后我需要对男性/女性的数据进行基本统计。我想一旦我正确过滤了列表,我就知道该怎么做。我将不胜感激任何建议、解释或建设性反馈。

标签: pythondatefilternested

解决方案


以下是按月对患者分组的可能解决方案:

patients_by_month = {month: [] for month in range(1, 13)}
for patient in patients:
    mm = int(patient[2].split('/')[1])
    patients_by_month[mm].append(patient)

我在您的示例上运行此代码然后patients_by_month是:

{1: [['Milos', 'Jones', '15/01/20', 'male', 'smoker', '210']],
 2: [['Denise', 'Ross', '13/02/20', 'female', 'non-smoker', '150']],
 3: [['Delia', 'Chan', '15/03/20', 'female', 'non-smoker', '170']],
 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], 10: [], 11: [], 12: []}

具体来说,patients_by_month是一个将每个月映射到患者列表的字典。


推荐阅读