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' (eg '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
使用生成器表达式,这可以写成一行:
select_s = ", ".join('ADD COLUMN %s FLOAT' % cat for cat in categories)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.