在递增for循环中递减变量

时间:2011-07-28 15:30:56

标签: 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]
        # ...

以下是我的脚本输出:

9
New Question Added!
8
10
New Question Added!
9
11

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

提前致谢,

麦克

2 个答案:

答案 0 :(得分: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
        # ...

答案 1 :(得分:1)

我非常厌恶手动更改索引变量让我想对此发表评论...... :) 如何改变它以在同一次迭代中完成两件事? 代码看起来有点奇怪,但你明白了。

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!"
        row = cursor.fetchone() # re-fetch to get the PK

    # Entry will exist now
    print "Getting Existing Entry"

    qpID = row[0]
    # ...

并尝试解释为什么递减“i”不起作用:

for循环并没有真正增加变量。它只是从您给出的序列中选择下一个值(由范围函数生成)。因此,如果序列为[9,10,11,12],它将按顺序选择它们。变量“i”将获得下一个值,前一个将被丢弃。没有增加或减少会影响这一点。