Skip to content
Advertisement

Splitting a date string within a Nested List to group lists by the month – Python

This is a homework assignment. I am not allowed to use libraries etc. The purpose is to learn and understand nested lists, loops and filtering by conditionals in Python.

I have a nested list of data, a short extract is below. It is 200 lines long.

JavaScript

I need to be able to filter the list by gender and the month. Convert the [5] element in each list to an integer ready.

To filter by gender I have written this code:

JavaScript

I have converted the element to an integer using :

JavaScript

Both work and output what I need.

However, I am trying to split the data into strings and convert to integers so I can filter by month. I used similar logic to above but I can’t make it work properly.

JavaScript

This gives me an error ” IndexError: list index out of range”

If I use the code:

JavaScript

It splits the date into “MM”, “DD”, “YY” but I lose the other data.

When I do get it split, I need to convert the date strings into integers, then using a loop for range(1,13) go through and group by the month. Then I need to perform basic statistics on the data for male/female. I think I know how to do that once I have filtered the lists correctly. I would appreciate any advice, explanations or constructive feedback.

Advertisement

Answer

let me tell you what you’re doing wrong here –

JavaScript

here’s in each for loop call i.e 0,1,2. You’re trying to update the last row -> patients[2].

patients[2] = [‘Denise’, ‘Ross’, ’13/02/20′, ‘female’, ‘non-smoker’, ‘150’]

patients[2] value will change if you do something like this inside for loop.

Let’s do this instead –

JavaScript

The above statement will give you another list –

JavaScript

Now, if you wanna assign this value back to the original list at a specific index i.e 2 of each row. you can do something like this

JavaScript

This will print –

JavaScript

To Extract months.

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement