Skip to main content
 首页 » 编程设计

python之无法弄清楚为什么数据结构在 Python 中被修改

2025年05月04日10zfyouxi

对于家庭作业,我正在经历各种测试,但无法找出以下代码的内容:

grammar = [  
    ("exp", ["exp", "+", "exp"]), 
    ("exp", ["exp", "-", "exp"]), 
    ("exp", ["(", "exp", ")"]), 
    ("exp", ["num"]), 
    ] 
 
 
def expand(tokens, grammar): 
    result = [] 
    for pos in range(len(tokens)): 
        print "pos = " + str(pos) 
        rulec = 0 
        for rule in grammar: 
            # hmmmm 
            print "rule = " + str(rule) 
            if tokens[pos] == rule[0]: 
                print "token matches rule!" 
                if pos == 0: 
                    for i in range(1,len(rule)): 
                        result.append(rule[i]) 
                else: 
                   for i in range(1,len(rule)): 
                        result[rulec].extend(rule[i])                 
            else: 
                print "token doesn't match rule" 
                if pos == 0: 
                    print "First instance" 
                    result.append([tokens[pos]]) 
                else: 
                    print "Appending..." 
                    #result[rulec].extend(copy.copy(tokens[pos])) 
                    result[rulec].extend('abc') 
            print "result so far = " + str(result) 
            print "grammar so far = " + str(grammar) 
            rulec += 1 
    print "result = " + str(result) 
    for i in result: 
        yield i 
 
depth = 1 
utterances = [["exp","a","exp"]] 
for x in range(depth): 
    for sentence in utterances: 
        utterances = utterances + [ i for i in expand(sentence, grammar)] 
 
for sentence in utterances: 
    print sentence 

如果我执行上面的操作,我希望得到这个:

['exp', 'a', 'exp'] 
['exp', '+', 'exp', 'a', 'b', 'c', 'exp', '+', 'exp'] 
['exp', '-', 'exp', 'a', 'b', 'c', 'exp', '-', 'exp'] 
['(', 'exp', ')', 'a', 'b', 'c', '(', 'exp', ')'] 
['num', 'a', 'b', 'c', 'num'] 

但是,我实际上明白了:

['exp', 'a', 'exp'] 
['exp', '+', 'exp', 'a', 'b', 'c', 'exp', '+', 'exp', 'a', 'b', 'c'] 
['exp', '-', 'exp', 'a', 'b', 'c', 'exp', '-', 'exp', 'a', 'b', 'c'] 
['(', 'exp', ')', 'a', 'b', 'c', '(', 'exp', ')', 'a', 'b', 'c'] 
['num', 'a', 'b', 'c', 'num', 'a', 'b', 'c'] 

出于某种原因我无法理解,当我在 [["exp","a","exp"]] 中的 'exp' 之间传递一个纯字符串(例如,'a')时,字符串被添加到最后。我放入了一堆打印语句,看起来一旦 pos==1 并且代码附加到结果列表,它也会附加到语法列表。但是,对于我的一生,我无法弄清楚为什么。我没有看到连接。

如果这有帮助,当我运行代码时 - 问题似乎出在这里:

pos = 1 
rule = ('exp', ['exp', '+', 'exp']) 
token doesn't match rule 
Appending... 
result so far = [['exp', '+', 'exp', 'a'], ['exp', '-', 'exp'], ['(', 'exp', ')'], ['num']] 
grammar so far = [('exp', ['exp', '+', 'exp', 'a']), ('exp', ['exp', '-', 'exp']), ('exp', ['(', 'exp', ')']), ('exp', ['num'])] 
  1. 问题 #1 - 结果不应该在末尾有额外的“a” 第一个嵌入列表
  2. 问题 2 - 为什么要修改语法?

我错过了什么? --吉姆

请您参考如下方法:

问题是您要遍历话语并同时附加到它。尝试这样的事情:

sentences = [] 
for x in range(depth): 
  for sentence in utterances: 
    sentences = sentences + [ i for i in expand(sentence, grammar)] 
 
for sentence in sentences: 
  print sentence