【问题标题】:Change list with one element to tuple将具有一个元素的列表更改为元组
【发布时间】:2021-09-17 14:34:26
【问题描述】:

我需要将列表转换为元组我将这个元组传递给 sql in 子句。当列表中只有一个元素时,元组正在检索额外的元素,我们如何避免这种情况。我将列表引用到下面的元组,但无法找到避免额外元素的答案

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

请告知合适的解决方案

【问题讨论】:

  • 接收一个额外的元素是什么意思?您正在拆分一个字符串并且分隔符存在,因此您会得到一个包含两个元素的列表。元组不会神奇地消除实际结果。
  • 不要使用插值来构造您的查询。使用您的 SQL 库提供的任何方法创建参数化查询,例如 cursor.execute("select * from table1 where task_id in %s", (t,))

标签: python python-3.x


【解决方案1】:

如果你想要的只是一个带参数的查询,那么不要使用元组,单个元素的元组将有一个逗号。

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

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

【讨论】:

    【解决方案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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 2018-11-27
      相关资源
      最近更新 更多