在python + psycopg2中,可以转换使用内联for循环的这行代码:
args_str = ','.join(cur_psql.mogrify("(%(customer_id)s, %(customer_name)s, %(contact_name)s, %(address)s, %(city)s, %(postal_code)s, %(country)s)", row) for row in cur_msql)
在迭代for循环时,允许进行更多操作的一段代码,但仍然获得相同的输出(包含所有数据的单个对象 - > args_str)?例如:
for row in cur_msql:
# additional operations eg.:
if row['customer_name'] == NULL:
row['customer_name'] = row['customer_name']
args_str =+ ','.join(cur_psql.mogrify("(%(customer_id)s, %(customer_name)s, %(contact_name)s, %(address)s, %(city)s, %(postal_code)s, %(country)s)", row)
答案 0 :(得分:1)
此代码累积在每个" mogrified"的列表中。值然后使用join()
将它们组合在一起:
args = []
for row in cur_msql:
# additional operations eg.:
if row['customer_name'] == NULL:
row['customer_name'] = row['customer_name']
args.append(cur_psql.mogrify("(%(customer_id)s, %(customer_name)s, %(contact_name)s, %(address)s, %(city)s, %(postal_code)s, %(country)s)", row))
args_str = ','.join(args)
它应该创建一个等效的args_str
来:
args_str = ','.join(cur_psql.mogrify("(%(customer_id)s, %(customer_name)s, %(contact_name)s, %(address)s, %(city)s, %(postal_code)s, %(country)s)", row) for row in cur_msql)
(N.B。我在上面将x
更改为row
。)
该字符串实际上是否是您需要/想要的另一个问题。