python - 在 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':[]
}
解决方案
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': []}
推荐阅读
- python-3.x - matplotlib.animation - 在曲线上移动点
- c++ - GNU LD 在使用 C++ 标准库时出错
- angular - NX.Dev 从 11 迁移到 12 失败并显示“EBUSY:资源繁忙或锁定”
- python - 不可更改的 Python 类实例属性
- javascript - 为什么在 map() 方法中使用 { } 会返回未定义的数组?
- ios - 将 HTTP 请求正文放入“数据”:{}?
- java - 如何反序列化列表列表?
- css - CSS过渡不适用于标签
- javascript - Java 脚本图像更改
- html - 需要输入单选按钮 - 仅设置星号而不是单选按钮