在递增的for循环中递减变量
在我的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方法来实现我想做的事情吗?
提前谢谢你,
Mike
2 个回答
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循环其实并不是在增加这个变量的值。它只是从你给定的序列中选择下一个值(这个序列是通过range函数生成的)。比如,如果序列是[9,10,11,12]
,它会按顺序选择这些值。变量“i”会得到下一个值,而之前的值会被丢弃。无论你怎么增加或减少,都不会影响这个过程。
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
# ...