【问题标题】:Decrement a variable in an incrementing for loop在递增的 for 循环中递减变量
【发布时间】:2011-10-15 06:01:01
【问题描述】:

在我的 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 方式是什么?

提前致谢,

迈克

【问题讨论】:

    标签: python


    【解决方案1】:

    为什么不使用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
            # ...
    

    【讨论】:

    • 它有效且简单。我喜欢。现在更好的问题是为什么使用 for 循环在我的脑海中根深蒂固。谢谢。
    【解决方案2】:

    我非常讨厌手动更改索引变量,这让我想对此发表评论... :) 将其更改为在同一迭代中完成两件事怎么样? 代码看起来有点奇怪,但你明白了。

    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 函数生成)。因此,如果 secquence 是[9,10,11,12],它将按顺序选择这些。变量“i”将获得下一个值,而前一个值将被丢弃。没有增加或减少会影响这一点。

    【讨论】:

      猜你喜欢
      • 2014-09-10
      • 2014-02-03
      • 1970-01-01
      • 2020-02-10
      • 1970-01-01
      • 1970-01-01
      • 2017-01-26
      • 1970-01-01
      • 2020-01-21
      相关资源
      最近更新 更多