我在 Python3 中有两个列表,可以插入 SQLite 数据库。 以下代码有效,但我确信有更好的方法。
cur.execute("CREATE TABLE my_table (id INT, vegetables TEXT, fruits TEXT)")
ls_vegetables = ['artichoke ', 'broccoli', 'celery']
ls_fruits = ['apple', 'banana', 'coconut']
# Vegetables loop
id = 1
for v in ls_vegetables:
cur.execute("INSERT INTO my_table(ID, vegetables) VALUES (?,?)", (id,v))
id += 1
conn.commit()
# Fruits loop
id=1
for f in ls_fruits:
cur.execute ("UPDATE my_table SET fruits=? WHERE ID=?", (f,id))
id += 1
conn.commit()
我可以只有一个循环吗?
这是我桌子的草图:
+----+------------+---------+
| id | vegetables | fruits |
+====+============+=========+
| 1 | artichoke | apple |
+----+------------+---------+
| 2 | broccoli | banana |
+----+------------+---------+
| 3 | celery | coconut |
+----+------------+---------+
答案 0 :(得分:0)
如果您确定ls_vegetables
和ls_fruits
的长度相等,则可zip
他们并使用一个循环:
cur.execute("CREATE TABLE my_table (id INT, vegetables TEXT, fruits TEXT)")
ls_vegetables = ['artichoke ', 'broccoli', 'celery']
ls_fruits = ['apple', 'banana', 'coconut']
# Vegetables loop
id = 1
for v,f in zip(ls_vegetables,ls_fruits):
cur.execute("INSERT INTO my_table(ID, vegetables) VALUES (?,?)", (id,v))
cur.execute ("UPDATE my_table SET fruits=? WHERE ID=?", (f,id))
id += 1
conn.commit()
答案 1 :(得分:0)
你可以用任何循环的单一语句来完成所有这些:
cur.executemany("INSERT INTO my_table(ID, vegetables, fruits) VALUES (?,?,?)",
((i, v, f) for (i, (v, f)) in enumerate(zip(vegetables, fruits), 1)))
补充:根据需要编辑将索引,蔬菜和水果扩展为扁平的3项元组,而不是2项元组,其第二个arg本身就是一个元组。)