将具有一个元素的列表更改为元组

2024-10-03 21:33:48 发布

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

我需要将一个列表转换为元组,我要将这个元组传递给一个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解决方案


Tags: to答案in元素convert列表情况query
2条回答

正如@chepner所说的,不要使用插值来构造查询。例如,使用sqlite3,您可以将任何变量作为参数传递,以便?将替换为元组中的相应参数:

cursor.execute("select * from table1 where task_id in ?", t)

此外,“('10030')中的“,”并不表示元组中有第二个项,而是表示它是一个元组:

thistuple = ("apple",)
print(type(thistuple)) #class tuple

#NOT a tuple
thistuple = ("apple") #class str
print(type(thistuple))

src:https://www.w3schools.com/python/trypython.asp?filename=demo_tuple_one_item

如果您只需要一个带参数的查询,那么不要使用元组,一个元素元组将有一个逗号

根据您的方法,您可以这样做(使用join):

l = ['10030']
query_param = ",".join(l)
query = f'select * from table1 where task_id in ({query_param})  query_temp'
print(query)

输出:

select * from table1 where task_id in (10030) query_temp

如果列表包含多个元素,则:

l = ['10030','111','22']
query_param = ",".join(l)
query = f'select * from table1 where task_id in ({query_param})  query_temp'
print(query)

输出:

select * from table1 where task_id in (10030,111,22) query_temp

相关问题 更多 >