gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:42:57 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com