在递增for循环中递减变量

Mik*_*old 1 python

在我的python脚本中,我通过从索引9开始的列表(headerRow)进行迭代.我想检查它是否已经在数据库中,如果没有,则将其添加到具有自动入侵主键的数据库中.然后我想再次通过循环发送它以检索它的主键.

for i in range (9, len(headerRow)):
    # Attempt to retrieve an entry's corresponding primary key.
    row = cursor.fetchone()
    print i

    if row == None: # New Entry
        # Add entry to database
        print "New Entry Added!"
        i -= 1 # This was done so that it reiterates through and can get the PK next time.
        print i

    else: # Entry already exists
        print "Existing Entry"
        qpID = row[0]
        # ...
Run Code Online (Sandbox Code Playgroud)

这是我的脚本的输出:

9
New Question Added!
8
10
New Question Added!
9
11
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我的问题是range()并不关心现有的值i是什么.做我想做的事情的首选python方法是什么?

提前致谢,

麦克风

Pat*_*ick 6

为什么不使用while循环?

i=9
while (i<len(headerRow)):
    # Attempt to retrieve an entry's corresponding primary key.
    row = cursor.fetchone()

    if row == None: # New Entry
        # Add entry to database
        print "New Entry Added!"
    else: # Entry already exists
        print "Existing Entry"
        qpID = row[0]
        i += 1
        # ...
Run Code Online (Sandbox Code Playgroud)