自动 python

Automatic in python

我一直在 python 研究自动化,但我在创建原理图时遇到了一些问题。

如果输入数据为(EV为偶数OD为奇数):

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

我正在尝试创建一个基于字典的示意图,这样对于偶数和奇数,都有嵌套的字典

虽然我在想出点子时遇到了很多麻烦

这个怎么样:

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')