首页 > 解决方案 > 从python代码中获取列表索引超出范围

问题描述

我正在尝试从列列表和值列表动态构建 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 )

一切正常

标签: pythonsql

解决方案


你可以改用这个:

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)

推荐阅读