I use Python/MySQLdb frequently and often format a list of categories for MySQL. The below code turns a list of categories into ‘ADD COLUMN a FLOAT, ADD COLUMN b FLOAT, ADD COLUMN c FLOAT’. I want to figure out how best to simplify this piece of code, allowing for arbitrary change to generic string ‘s’ (e.g. ‘ADD COLUMN %s FLOAT’ could easily be ‘%s = %d’ or “%s = ‘%s'”). Is there some form of list comprehension which works?
categories = ['a','b','c']
select_l = []
for cat in categories:
s = 'ADD COLUMN %s FLOAT' % (cat)
select_l.append(s)
select_s = ", ".join(select_l)
I could create a method, but there seems to many examples where it wouldn’t handle a specific need. Thanks
Using a generator expression, this can be written as a one-liner: