We're already familiar with nested lists: they are simply lists of lists. Here's an example:
rhymes = [['cat', 'hat', 'fat'], ['mouse', 'house', 'louse'], ['be', 'see', 'key', 'he']]
This is a list with three elements: ['cat', 'hat', 'fat']
, ['mouse', 'house', 'louse']
, and ['be', 'see', 'key', 'he']
. We can get the second element as follows:
rhymes[1]
Here is how we can get the third element of the second list:
rhymes[1][2]
This is the same as going
['mouse', 'house', 'louse'][2]
Let's say that we have a list of lists that contains the dates of the visits each patient has made.
visits[i]
is the data for patient i
: the dates on which patient i visited the docotor
visits = [[2, 6], [3, 10], [15], [23], [14]]
So for example patient 1 visited the doctor on the 3rd and the 10th, for a total of two visits.
Now, let's write a program to get the maximum number of visits, for any patient (the answer in this case is 2, since no patient has visited the doctor more than twice)
max_visits = 0
for patient_data in visits:
num_visits = len(patient_data)
if num_visits > max_visits:
max_visits = num_visits
print(max_visits)
How about the patient who visited the most times? Now, we need to also store the index of the maximum
max_visits = len(visits[0])
max_ind = 0 #the index of the sickest patient
for i in range(len(visits)):
num_visits = len(visits[i])
if num_visits > max_visits:
max_ind = i
max_visits = num_visits
print("Patient", max_ind , "is the sickest")
Here's another option, if you remember about list.index
print(num_visits.index(max(num_visits)))
Now, write code that displays the indices of all the patients who had the largest number of visits.
Solution:
num_visits = [] #contains the number of visits
#for every patient
for patient_data in visits:
num_visits.append(len(patient_data))
max_visits = max(num_visits)
for i in range(len(num_visits)):
if num_visits[i] == max_visits:
print(i, "is one of the sickest patients")