不可理解的错误与三个打印以下

2024-05-28 18:49:53 发布

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

我的字典定义如下:

SN = {}
SN[0] = {'verb' : 1 }

在我的函数中,我做了如下3print

print graph
print state
print graph[state]

(我对这些变量不做任何其他操作)它返回:

SN  
0  
S

这怎么可能?为什么不回来

SN
0
{'verb' : 1}  

整个代码:

abstraction= {}
abstraction['de'] = ['déterminant']
abstraction['le'] = ['déterminant']
abstraction['un'] = ['déterminant']
abstraction['beau'] = ['adjectif', 'substantif']
abstraction['dodu'] = ['adjectif', 'substantif']
abstraction['grand'] = ['adjectif', 'substantif']
abstraction['méchant'] = ['adjectif', 'substantif']
abstraction['noirs'] = ['adjectif', 'substantif']
abstraction['petit'] = ['adjectif', 'substantif']
abstraction['desseins'] = ['substantif']
abstraction['loup'] = ['substantif']
abstraction['poulet'] = ['substantif']
abstraction['gosse'] = ["n'importe quoi"]
abstraction['mange'] = ['verbe']
abstraction['dort'] = ['verbe']


SN = {}
SN[0] = {'déterminant' : 1 }
SN[1] = {'adjectif' : 1, 'substantif' : 2 }
SN[2] = {'adjectif' : 3, '' : 'ok' }
SN[3] = {'' : 'ok' }

SV = {}
SV[0] = {'verbe' : 1}
SV[1] = {'transitions' : 'SN', '' : 'ok'}
SV[2] = {'' : 'ok'}


def transitions(data, graph, state = 0, transit = []) :
    print 'data avt if data :'
    print data
    if data : 
        if 'transitions' in graph[state] :
            return transitions(data, graph[state]['transitions'], 0, transit)
        symbol = data[0]
        if symbol not in abstraction.keys() : 
            return ['impossible, un des mots n\'est pas reconnu par l\'automate'] 
        for a in abstraction[symbol] : # loop on abstractions
            print graph
            print state
            print graph[state]
            if a in graph[state] :
                state = graph[state][a]
                return transitions(data[1:], graph, state, transit + [a])
        else :  
            return transit + [symbol] + ['impossible'] 
    else : 
        if '' in graph[state] :
            return transit + [graph[state]['']]
        else : return transit + ['impossible']

Tags: indatareturnifokgraphstateprint
1条回答
网友
1楼 · 发布于 2024-05-28 18:49:53

我认为你这里的问题是graph == "SN",而不是(正如你显然预期的那样)graph == SN

换句话说,graph引用值为"SN"str对象,也被名称SN引用的dict对象

因此graph[0]是字符串"SN"中的第一个字符,即字母"S"

graph == SN的情况下,来自

print graph
print state
print graph[state]

可能是:

{0: {'verb': 1}} # note: not 'SN'
0
{'verb': 1}

编辑:

现在您已经发布了代码,本节:

SN = {}
SN[0] = {'déterminant' : 1 }
SN[1] = {'adjectif' : 1, 'substantif' : 2 }
SN[2] = {'adjectif' : 3, '' : 'ok' }
SN[3] = {'' : 'ok' }

创建字典

SN = {0: {'déterminant': 1}, 1: {'adjectif': 1, 'substantif': 2},
      2: {'adjectif': 3, '': 'ok'}, 3: {'': 'ok'}}

但是,在下一部分:

SV[1] = {'transitions' : 'SN', '' : 'ok'}

将字符串'SN'赋给键'transitions',而不是实际的字典SN。应该是:

SV[1] = {'transitions': SN, '': 'ok'}
                      # ^ no quote marks

此外,由于所有键都是从零开始的整数,因此可以考虑使用列表而不是字典,例如:

SN = []
SN.append({'déterminant': 1})
SN.append({'adjectif': 1, 'substantif': 2})
...

相关问题 更多 >

    热门问题