首页 > 解决方案 > 在 python 中,一个列表像树拓扑一样转换为 dict

问题描述

在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':[]
}

标签: pythonpython-2.7

解决方案


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': []}





推荐阅读