此腳本的目的是學習如何將 lambda 函式與map 結合使用。我嘗試向 sqlite TABEL 的所有列插入一個字串,但沒有顯示錯誤,但值沒有改變。
def get_columns(self):
res=self.get_cursor().execute("SELECT * FROM EVENTS")
names = list(map(lambda x: x[0], res.description))
return names`
def update_to_last(self,column:str,data:str):
c=self.get_cursor()
print(column,data)
c.execute(f"UPDATE EVENTS SET '{column}'='{data}' WHERE ID ='(SELECT last_insert_rowid())'")
self.conn.commit()
if __name__ =="__main__":
d=DB()
columns=d.get_columns()
#this pile of map and lambda's ment to first get all of the columns names
#then add to every string a pair of some fictionary "data" to a list
#then the list is sent to update
map(lambda x:d.update_to_last(x[0],x[1]),(list(map(lambda column:[column,"data"],columns))))
uj5u.com熱心網友回復:
map不創建結果串列。當您迭代map實體時,它會按需生成專案。您不會迭代map實體,因此update_to_last永遠不會被呼叫。
不要map用于副作用。使用常規for回圈。
# No need to turn the map instance into a list first; you
# can iterate over the map directly.
for x in map(lambda column: [column, "data"], columns):
d.update_to_last(x[0], x[1])
當然,既然"data"是 的固定值x[1],你真的根本不需要map。
for column in columns;
d.update_to_last(column, "data")
另一方面,如果d.update_to_last產生了一個有趣的回傳值,你想將它存盤在一個串列中,你可能會做一些類似的事情
from itertools import repeat
x = list(map(d.list_to_update, columns, repeat("data")))
雖然串列理解像
x = [d.list_to_update(c, "data") for c in columns]
會更可取。
uj5u.com熱心網友回復:
你的意思是這樣的嗎?(相應地更改列名id)
c.execute(f"UPDATE EVENTS SET '{column}'='{data}' WHERE id = (SELECT last_insert_rowid())")
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/393717.html
上一篇:帶反斜杠的字串到字典
