父子映射Python字典

2024-05-20 23:50:11 发布

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

我很难编出一本关于亲子标记的词典。你知道吗

我有一本这样的字典:

d = {
'A': ['Blue'],
'B': ['A'],
'C': ['A'],
'D': ['C'],
}

这是我的逻辑或思维过程:如果一个键是'Blue',它就是父键,并得到一个0的标志。如果valued.keys()中,它将获得一个1标志。我被困在孙子孙女身上。这是我现在的代码,是我的头撞在墙上几个小时的结果。你知道吗

level = 0
while level < 1000:
    for key, value in d.items():
        if value[0] == 'Set':
            if len(value) == 1:
                value.extend([level])
        elif len(value) >= 2:
            continue
        elif value[0] in d.keys():
            value.extend([level])
        level += 1

结果是:

A:      ['Blue', 0]
B:      ['A', 1]
C:      ['A', 2]
D:      ['D', 3]

DC的孙子,应该有一个2的标志,CA的子级,应该有一个2的值,就像另一个子级B。你知道吗

这样做的目的是创建正确的标志,无论有多少个孙子或曾孙级别。你知道吗

这里的数据是嵌套的。我有一个奇怪的数据库,必须使用某个专有模块来迭代通过类属性提供给我的查找表。所以,代码是

while parent:
    ...block of code for parent...
    ...insert same structure here if not the parent... 
    ...statement at end of parent block...

因此,子循环可能如下所示:

while parent:
    ...block of code for parent...
    while child:
       ...block of code for child...
       ...variable for block insertion...
       ...statement at end of child block...
    ...statement at end of parent block...

...statement at end of parent/child block...next()类似,但使用我需要使用的专有模块。你知道吗

因此,映射器将用于让程序知道要使用此结构创建多少嵌套while循环。我还没有插入嵌套块,但我知道这是可以做到的。:)

我很想向能够解释如何创建映射器部分的人学习。你知道吗

谢谢你!你知道吗


Tags: ofchildforifvalue标志codeblue
3条回答

这段代码修改现有的child:parent字典,将深度标志添加到每个列表的末尾。它将正常工作(在python2和python3中),无论键的处理顺序如何。在Python3.6之前的版本中,字典不一定保留键的插入顺序,并且键的顺序可以从程序的一次运行更改到下一次运行。所以我对条目做了一些修改,以确保它的行为符合预期。你知道吗

src = {
    'D': ['C'],
    'B': ['A'],
    'A': ['Blue'],
    'C': ['A'],
}

def get_depth(d, k):
    v = d[k]
    if len(v) == 2:
        return v[1]
    else:
        parent = v[0]
        depth = 0 if parent == 'Blue' else get_depth(d, parent) + 1
        v.append(depth)
        return depth

for k in src:
    get_depth(src, k)

print(src)    

Python 3.6输出

{'D': ['C', 2], 'B': ['A', 1], 'A': ['Blue', 0], 'C': ['A', 1]}
d = {
  'A': ['Blue'],
  'B': ['A'],
  'C': ['A'],
  'D': ['C'],
}

output = {}
for k, v in d.items():
    output[v[0]] = output.get(v[0], [])
    output[v[0]].append(k)

output
#=> {'Blue': ['A'], 'A': ['C', 'B'], 'C': ['D']}

我不确定我是否完全理解预期的输出应该是什么,但这可能会有所帮助

for key, value in d.items():
    if value[0] == 'Set':
        if len(value) == 1:
            value.extend([0])
    elif len(value) >= 2:
        continue
    elif value[0] in d.keys():
        newlevel = d[value[0]][1] + 1
        value.extend([newlevel])

相关问题 更多 >