python - 从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 )
一切正常
解决方案
你可以改用这个:
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 - 微调超参数不会提高分类器的分数
- angular - 角 9 SSR | 无法访问 ads.txt 文件
- postgresql - 如何在 PostgreSQL 中通过 cmd 使用 pg_restore 命令恢复 .bak 文件?
- unity3d - 为子像素阴影映射编码几何信息
- python - 如何处理 Python Selenium 中的“消息:过时的元素引用:元素未附加到页面文档”
- javascript - Javascript - 为存储在用户计算机上的静态网页读取/写入设置的推荐/安全方式是什么?
- html - 为什么叠加的图片和标志+文字不起作用?
- ruby-on-rails - 与乘客一起在生产中使用 resque 时,没有路线匹配 [GET] "/resque/overview"
- c++ - 在字符串中查找模式
- google-apps-script - Google-App-Scripts-Search files 找不到电子表格