python - 从Python代码中获取列表索引超出范围

标签 python sql

我正在尝试从列列表和值列表动态构建 SQL WHERE 子句。为此,我从以下代码开始:

sql_cols = ['description', 'height', 'weight', 'class' ]

sql_vals = [ 1, 2, 3, 4 ]

sql_test = " and".join( " f = :{}".format(x) for x in sql_vals )

print sql_test

这给了我以下结果:

root@scar$ python testme.py
 f = :1 and f = :2 and f = :3 and f = :4

但是我想要得到的是这样的:

 `DESCRIPTION = :1 and HEIGHT = :2 and WEIGHT = :3 and CLASS = :4`

如何做到这一点?

编辑: 将代码更改为:

sql_test = "and".join( sql_cols[x - 1] + "= :{}".format(x) for x in sql_vals )

一切顺利

最佳答案

你可以用这个代替:

sql_cols = ['description', 'height', 'weight', 'class' ]

sql_vals = [ 1, 2, 3, 4 ]

sql_test = " and ".join("{} = :{}".format(*x) for x in  zip(sql_cols,sql_vals) )

print (sql_test)

关于python - 从Python代码中获取列表索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57205969/

相关文章:

MySQL 排除和要求

sql - 如果没有找到匹配项,简单的 SQL 查询将返回 null

sql - 使用 Dapper 自动映射输出参数

python - 解读 Sentry 频率图

python - 未找到 libtorrent 模块

python - 将数据框中的整列向上或向下舍入

sql - PostgreSQL 获得最小计数(*)?

php - SQL查询不返回计数值

python - 为什么我不能只添加 Content-Type :text/html to a text file when Python can?

python - 从python中的二进制数据中获取unicode字符串