增量发生在它应该发生之前

2024-09-21 19:47:41 发布

您现在位置:Python中文网/ 问答频道 /正文

a_string = 'abc'

destination = [2, 3]    

edges = { (1, 'a') : [2, 3],
          (2, 'a') : [2],
          (3, 'b') : [4, 3],
          (4, 'c') : [5] }

def make(a_string, destination, edges):
    n = 0
    while n + 1 < len(a_string):
        letter = a_string[n]
        letter2 = a_string[n + 1]
        for d in destination:                              # (1)
            if (d, letter2) in edges:
                for state in edges[(d, letter2)]:
                    destionation.append(state)
            destination.remove(d)
        n += 1                                             # (2)
    return destination

代码返回[],但是我希望看到[5],所以我认为问题是它意外地增加了n,然后使letter2改变。 为什么这个代码在完成for循环(在位置1)之前增加n(在位置2)?你知道吗


Tags: 代码inforstringmakelenifdef
3条回答

您也可以在字符串上迭代,并且使用字符串的index方法可以获取字符的下一个位置。你知道吗

将这两者结合起来,可以简化初始外循环:

def make(a_string, destination, edges):

    for letter in a_string:
        while a_string.index(letter)+1 < len(a_string):
            next_letter = a_string[a_string.index(letter)+1]

此外,您不应该将变量命名为string,因为它是模块的名称。你知道吗

在循环完成之前,n不会递增。 您可能缺少的是while循环检查n+1而不是n

编辑现在我们有更多信息:

问题是您正在从具有未定义行为的迭代器中删除项。你知道吗

试试看

for d in destination[:]:

这是整个数组上的切片运算符,因此它充当复制构造函数。 您现在正在另一个对象上循环,删除应该是安全的。你知道吗

如果在循环末尾不加1到n,循环条件保持不变,循环将永远执行。它不是在for循环中执行的,而是在while循环体中执行的。(缩进决定一行属于哪个代码块!)你知道吗

相关问题 更多 >