循环python的多个变量

Eli*_*ith 1 python variables arguments loops for-loop

我正在尝试创建一个for循环来将用户定义的多个关联变量写入数据库,有没有办法做这样的事情?

import sqlite3 as lite
import sys

names = ( "John", "Sal", "Bill" )
ids = ( 123, 321, 231 )

con = lite.connect('test.db')
cur = con.cursor()

**for x in names and y in id:**

  cur.execute("INSERT INTO People(Name, ID) VALUES('%s', %d)" % x y)
Run Code Online (Sandbox Code Playgroud)

Kev*_*vin 8

要同时迭代多个迭代,请使用zip.

>>> names = ( "John", "Sal", "Bill" )
>>> ids = ( 123, 321, 231 )
>>> for x,y in zip(names, ids):
...     print x,y
...
John 123
Sal 321
Bill 231
Run Code Online (Sandbox Code Playgroud)