我有一个字典定义如下:
SN = {}
SN[0] = {'verb' : 1 }
在我的函数中,我按如下方式生成3 print
:
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']
答案 0 :(得分:3)
我认为您的问题是graph == "SN"
,而不是(正如您所期望的那样)graph == SN
。
换句话说,graph
引用的str
对象的值为"SN"
,不 dict
对象也被引用名称SN
。
因此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})
...