繁体   English   中英

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

[英]Change list with one element to tuple

我需要将列表转换为元组我正在将此元组传递给 sql 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"""

请告知合适的解决方案

就像@chepner 所说的那样,不要使用插值来构造您的查询。 例如,对于 sqlite3,您可以将 any 变量作为参数传递,以便每个 ? 将被元组中的相应参数替换:

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))

源代码: 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

如果列表包含超过 1 个元素,则:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM