在For循环中更新索引值 [英] Updating Index Value in For Loop

查看:66
本文介绍了在For循环中更新索引值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于一个列表中的元素,我想更新我的for循环中的索引值.我相信我已经做到了,但是我的Python脚本似乎没有输出正确的值,而且我不知道为什么:

Based on an element found in a list, I'd like to update the index value in my for loop. I believe I've done this, but my Python script doesn't seem to be outputting the correct values and I cannot figure out why:

我的列表如下:

dataXY = [['6', 'c', '3', '7', '2', '9', '1', '7'],['8', '4', 'c', '7', '9', '3', '4', '7', '1', '2']]

适用于此的代码是:

for lists in dataXY:
    XYbezier = []
    final_lists = []
    for datum in range(len(lists)):
        if lists[datum] == 'c':
            for k in range(-1,4):
                if k != 0:
                    XYbezier.append(lists[datum+k])
        else:
            if lists[datum-1] == 'c':
                datum += 3
                if datum != len(lists):
                    final_lists.append(lists[datum])
            else:   
                final_lists.append(lists[datum])
    print datum

它的打印内容是:1个53456701个2个6456789

What it's printing is this: 1 5 3 4 5 6 7 0 1 2 6 4 5 6 7 8 9

由于某种原因,索引值被重置,但随后又被还原(从它从1跳到5然后又回到3的方式)我不明白为什么这样做,我需要将索引值设置为跳3个位置并永久更新,而不是将自身恢复到原始值.

For some reason, the index value is being reset, but then restored (from how it skips to 5 from 1 and then goes back to 3) I don't understand why it's doing this, and I need the index value to jump 3 places and permanently update instead of restoring itself back to its original value.

推荐答案

使用for循环时,将从列表中的值加载索引变量. range(x)创建列表 [0,1,2,...,x] ,因此在每次迭代中, datum (在您的的情况下)从该列表中获取新的数值.这会覆盖 datum 可能保存的任何值.

When you use a for loop, the index variable is loaded from values in a list. range(x) creates the list [0,1,2, ... ,x] so on each iteration, datum (in your case) gets a new numerical value off that list. This overrides any value that datum may hold.

您可以通过切换到 while 循环来实现目标:

You can accomplish your goal by switching to a while loop:

datum = 0
end = len(lists)
while datum < end:
    # do stuff

    # don't forget to increment datum
    datum += 1

这篇关于在For循环中更新索引值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆