在python中,一个列表像树形拓扑一样转换为dict

时间:2019-04-07 01:12:37

标签: python python-2.7

在python2.7中,我只有一个列表

['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q']

我需要转变成像这样的字典

{
'A':['B','C'],
'B':['D','E'],
'C':['F','G'],
'D':['H','I'],
'E':['J','K'],
'F':['L','M'],
'G':['N','O'],
'H':['P','Q'],
'I':[],
'J':[],
'K':[],
'L':[],
'M':[],
'N':[],
'O':[],
'P':[],
'Q':[]
}

6 个答案:

答案 0 :(得分:1)

使用zip()itertools.izip_longest(),您可以这样做:

代码:

import itertools as it

in_data = list('ABCDEFGHIJKLMNOPQ')
out_data = {k: list(v) if v else [] for k, v in
            it.izip_longest(in_data, zip(in_data[1::2], in_data[2::2]))}

import json
print(json.dumps(out_data, indent=2))

结果:

{
  "A": [
    "B", 
    "C"
  ], 
  "C": [
    "F", 
    "G"
  ], 
  "B": [
    "D", 
    "E"
  ], 
  "E": [
    "J", 
    "K"
  ], 
  "D": [
    "H", 
    "I"
  ], 
  "G": [
    "N", 
    "O"
  ], 
  "F": [
    "L", 
    "M"
  ], 
  "I": [], 
  "H": [
    "P", 
    "Q"
  ], 
  "K": [], 
  "J": [], 
  "M": [], 
  "L": [], 
  "O": [], 
  "N": [], 
  "Q": [], 
  "P": []
}

答案 1 :(得分:1)

您可以使用itertools

from itertools import chain, repeat

data = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q']
lists = [[first, second] for first, second in zip(data[1::2], data[2::2])]
result = {char: list(value) for char, value in zip(data, chain(lists, repeat([])))}

result

输出:

{'A': ['B', 'C'],
 'B': ['D', 'E'],
 'C': ['F', 'G'],
 'D': ['H', 'I'],
 'E': ['J', 'K'],
 'F': ['L', 'M'],
 'G': ['N', 'O'],
 'H': ['P', 'Q'],
 'I': [],
 'J': [],
 'K': [],
 'L': [],
 'M': [],
 'N': [],
 'O': [],
 'P': [],
 'Q': []}

答案 2 :(得分:1)

您可以通过索引关系创建树形拓扑字典:

def generateTree(arr):
    tree = {}
    for i, v in enumerate(arr):
        tree[v] = []
        if i * 2 + 1 < len(arr):
            tree[v].append(arr[i * 2 + 1])
        if i * 2 + 2 < len(arr):
            tree[v].append(arr[i * 2 + 2])
    return tree

输出: {'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F', 'G'], 'D': ['H', 'I'], 'E': ['J', 'K'], 'F': ['L', 'M'], 'G': ['N', 'O'], 'H': ['P', 'Q'], 'I': [], 'J': [], 'K': [], 'L': [], 'M': [], 'N': [], 'O': [], 'P': [], 'Q': []}

希望对您有所帮助,如有其他问题,请发表评论。 :)

答案 3 :(得分:1)

这是一种经过很好优化的老式方法,使用了下面的教程中所述的数组索引方法:https://www.geeksforgeeks.org/construct-complete-binary-tree-given-array/

第一行用子项的值填充非叶。第二行将叶子填充为空列表。我会注意到我们知道内部节点的数量是(len(values)// 2)。

values = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q']
dictionary = {values[i]:[values[2*i+1], values[2*i+2]] for i in range((len(values) // 2))}
dictionary.update({values[i]:[] for i in range((len(values) // 2) + 1, len(values))})

答案 4 :(得分:1)

alphabet=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q']

d={} # empty dictionary
counter=2
for i in range(0,len(alphabet)):
    if i==0: # at letter 'A' only
        lst=[alphabet[i+1],alphabet[i+2]] # lst that will be used as value of key in dictionary
    elif i<(len(alphabet)-1)/2: #  at letter 'B' through 'H'
        lst=[alphabet[i+counter],alphabet[i+counter+1]] # lst that will be used as value of key in dictionary
        counter+=1 # increment counter

    else: # all letters after 'H'
        lst=[] # an empty list that will be used as value of key in dictionary
    d[alphabet[i]]=lst # add 'lst' as a value for the letter key in the dictionary

print(d) # print the dictionary

# {'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F', 'G'], 'D': ['H', 'I'], 'E': ['J', 'K'], 'F': ['L', 'M'], 'G': ['N', 'O'], 'H': ['P', 'Q'], 'I': [], 'J': [], 'K': [], 'L': [], 'M': [], 'N': [], 'O': [], 'P': [], 'Q': []}




答案 5 :(得分:1)

尝试:

LL = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q']

dd = {}
for i,e in enumerate(LL):
    LLL   = []
    if ((i+1) + len(dd) < len(LL)): LLL = [LL[((i+1) + len(dd))], LL[((i+1) + len(dd))+1]]
    dd[e] = LLL

print dd

{'A': ['B', 'C'], 
'B': ['D', 'E'], 
'C': ['F', 'G'], 
'D': ['H', 'I'], 
'E': ['J', 'K'], 
'F': ['L', 'M'], 
'G': ['N', 'O'], 
'H': ['P', 'Q'], 
'I': [], 
'J': [], 
'K': [], 
'L': [], 
'M': [], 
'N': [], 
'O': [], 
'P': [], 
'Q': []}

更具可读性:

dd = {}   
for i,e in enumerate(LL):
        LLL   = []
        intv  = (i+1) + len(dd)           
        if (intv < len(LL)): LLL = [LL[(intv)], LL[(intv)+1]]
        dd[e] = LLL

print dd