用格式化的输出自动扩展Python列表 [英] Automagically expanding a Python list with formatted output

查看:91
本文介绍了用格式化的输出自动扩展Python列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道是否有一种方法可以自动在Python中用逗号分隔列表吗?我正在编写一些使用MySQLdb库的Python代码,并尝试使用某些键值动态更新MySQL数据库中的行列表.

Does anyone know if there's a way to automatically expand a list in Python, separated by commas? I'm writing some Python code that uses the MySQLdb library, and I'm trying to dynamically update a list of rows in a MySQL database with certain key values.

例如,在下面的代码中,我想让record_ids列表中的数字值扩展为SQL"IN"子句.

For instance, in the code below, I'd like to have the numeric values in the record_ids list expand into a SQL "IN" clause.

import MySQLdb
record_ids = [ 23, 43, 71, 102, 121, 241 ]

mysql = MySQLdb.connect(user="username", passwd="secret", db="apps")
mysql_cursor = mysql.cursor()

sqlStmt="UPDATE apps.sometable SET lastmod=SYSDATE() where rec_id in ( %s )"

mysql_cursor.execute( sqlStmt, record_ids )
mysql.commit()

任何帮助将不胜感激!

推荐答案

尝试:

",".join( map(str, record_ids) )

",".join( list_of_strings )通过用逗号分隔字符串来连接字符串列表

",".join( list_of_strings ) joins a list of string by separating them with commas

如果您有数字列表,map( str, list )会将其转换为字符串列表

if you have a list of numbers, map( str, list ) will convert it to a list of strings

这篇关于用格式化的输出自动扩展Python列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆