从python cod获取列表索引超出范围

2024-03-28 12:20:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从列列表和值列表动态构建一个SQLWHERE子句。为此,我从以下代码开始:

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\u test=“and”.join(sql\u cols[x-1]+”=:{}.format(x)for x in sql\u vals)

一切都成功了


Tags: and代码intestformat列表forsql
3条回答

您可以使用此选项:

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)

试试这个:

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)

试试这个:

sql_test = " and ".join("{} = :{}".format(x[0].upper(), x[1]) for x in zip(sql_cols,sql_vals) )

相关问题 更多 >