OldSteve
OldSteve

Reputation: 608

Formatting Contents Of A Variable Length List

Within our application there is a list of common medical conditions:-

conditionsList = ['Alzheimers', 'Asmatic', 'Arthtitis', \
   '', '', '' \
    'Cardiovascular', 'Other Musculoskelatal', 'Peripheral Artery Disease']

When a patient's details are added or updated there is a second screen where these conditions can be linked to a patient. These are stored in a MySQL database as simple Y/N values. These are then read in:-

conditionsVal = [row[i] for row in rows for i in xrange(1, 42)]

and a sub-list created

 listVal = [historyList[i] for i in xrange(len(historyList)) if historyVal[i] == 'Y'] 

The problem I have is how to format this new list into a sensible printout because any person may have no existing conditions but others may have a dozen or more.

The initial format used is HTML. This is subsequently converted to a PDF,via the utility wkhtmltopdf, for printing/e-mailing if required.The idea is to avoid line wraps, part lines, etc...

Upvotes: 1

Views: 298

Answers (1)

John Coleman
John Coleman

Reputation: 51998

There isn't a right answer or a wrong answer to this. You can decide how you want to format a list and then write a custom formatting function. Something like:

def formatStringList(ls):
    if len(ls) == 0:
        return 'None'
    elif len(ls) == 1:
        return ls[0]
    else:
        return ', '.join(ls[:-1]) + ', and ' + ls[-1]

Somewhat frivolous test:

lists = [[],['Cancer'],['Diabetes','Plague','AIDS','Ingrown Toenails']]

for i,ls in enumerate(lists,start = 1):
    print("Patient " + str(i) + " conditions: " + formatStringList(ls))

Output:

Patient 1 conditions: None
Patient 2 conditions: Cancer
Patient 3 conditions: Diabetes, Plague, AIDS, and Ingrown Toenails

If there are any empty strings in the list you could first filter them out.

You could get more sophisticated and decide on a maximum line length, introducing explicit line breaks ('\n') as needed. Try something. If you aren't happy with it -- tweak it.

Upvotes: 2

Related Questions