在python中自动

时间:2015-04-15 03:49:17

标签: python dictionary finite-automata

我一直在使用python中的自动机,但是我在创建原理图时遇到了一些麻烦。

如果输入数据是(其中EV是偶数且OD是奇数):

 EV|0|EV|1|OD
 OD|0|OD|1|EV

我试图创建一个基于字典的原理图,这样就偶数和奇数都有嵌套字典

虽然我在提出想法方面遇到了很多麻烦

1 个答案:

答案 0 :(得分:0)

这个怎么样:

data = 'EV|0|EV|1|OD;OD|0|OD|1|EV'

# output: {even: {0:even, 1:odd}, odd: {0:odd, 1:even}}

information = data.split(';')
output = {}
for piece in information:  # Each piece is like EV|0|EV|1|OD
    parts = piece.split('|')
    head = parts[0]  # Our dictionary key, eg. [EV]
    tail = parts[1:]  # Stuff that makes up the inner dict, e.g. [0, EV, 1, OD]

    # Use step = 2 to get key:value pairs from tail:
    inner = {tail[i]: tail[i+1] for i in range(0, len(tail)-1, 2)}

    if head not in output:
        output[head] = inner
    else:
        # What do we do here?
        pass

print(output)

收益率:{'EV': {'1': 'OD', '0': 'EV'}, 'OD': {'1': 'EV', '0': 'OD'}}

如果你想,在一开始,你可以这样做:

data = data.replace('EV', 'even').replace('OD', 'odd')