簡體   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