我需要将一个列表转换为元组,我要将这个元组传递给一个SQLIN子句。当列表中只有一个元素时,tuple正在检索额外的元素,我们如何避免这种情况。我将列表引用到下面的tuple,但无法找到答案以避免额外的元素
Convert list to tuple in Python
>>> taskid="10030"
>>> l = taskid.split(",")
>>> l
['10030']
>>> t = tuple(l)
>>> t
('10030',)
>>> query = f"""select * from table1 where task_id in {tuple(t)} ) query_temp"""
请告知apt解决方案
正如@chepner所说的,不要使用插值来构造查询。例如,使用sqlite3,您可以将任何变量作为参数传递,以便?将替换为元组中的相应参数:
此外,“('10030')中的“,”并不表示元组中有第二个项,而是表示它是一个元组:
src:https://www.w3schools.com/python/trypython.asp?filename=demo_tuple_one_item
如果您只需要一个带参数的查询,那么不要使用元组,一个元素元组将有一个逗号
根据您的方法,您可以这样做(使用join):
输出:
如果列表包含多个元素,则:
输出:
相关问题 更多 >
编程相关推荐