[enter image description here][1]I have a dataset that is a list of 3 nested lists (called "patients"). Each nested list contains a certain amount of observations. The first nested list contains 119 observations, the second one 9 and the third list contains 6 observations. These observations are dictionaries containing some keys such as "start time" and "end time".
Now I want to create a for loop to create a new list with 3 nested lists. I want each new nested list to only include the start times of that specific patient. So, 1 list that contains 3 lists with different sizes (119, 9 and 6)
However, when I try this, I get a list with 3 nested lists that all have the same size, all the nested lists include all 134 observations (119 9 6, called "start_times") . Is there somebody that can please help me with this?
`
start_times = [[] for i in range(3)]
for a in patients:
for b in a:
for c in range(3):
start_times[c].append(b['start'])
` [1]: https://i.stack.imgur.com/0us5J.png [2]: https://i.stack.imgur.com/yHEIl.png
CodePudding user response:
You'll want to use a nested list comprehension for this. I've changed the variable names for clarity, and added white space to make the structure clear:
start_times = [
[
observation['start']
for observation
in patient
]
for patient
in patients
]
CodePudding user response:
You probably want to do this instead:
start_times = [[]*3]
for idx, sublist in enumerate(patients):
for record in sublist:
start_times[idx].append(record["start"])