如何在Python中将列表转换为树? [英] How To Convert A List to A Tree in Python?
本文介绍了如何在Python中将列表转换为树?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何从嵌套列表中表示一棵树?
How i can represent a tree from a nested list?
L = [['bike', '2 * wheel+1* frame'], ['wheel', '1*rim+1*spoke+1*hub'], ['rim', 60],['spoke', 120]
Tree = ['bike', 2, ['wheel', 1, ['rim', 60], 1, ['spoke', 120], 1, ['hub', 2]]
说明:
在此示例中,自行车由2个轮子和1个框架制成, 车轮由1个轮圈,1个辐条和1个轮毂制成 ['rim',60]表示rim的价格为60.
In this example bike is made from 2 wheels and 1 frames, wheel is made from 1 rim,1spoke and 1 hub ['rim', 60] means that rim's price is 60.
我不明白如何将列表转换为树.
I could not understand how to convert the list to tree.
推荐答案
这是我要采取的步骤:
- 编写一个函数,使
f('2 * wheel+1* frame') == {'wheel': 2, 'frame': 1}
-
在整个列表上运行该函数以生成
- Write a function such that
f('2 * wheel+1* frame') == {'wheel': 2, 'frame': 1}
Run that function on the entire list to generate
[
('bike', {'wheel': 2, 'frame': 1}),
('wheel', {'rim': 1, 'spoke': 1, 'hub': 1}),
('rim', 60)
]
遍历此列表,并将其更改为:
Iterate over this list, and change it to:
[
('bike', {
('wheel', {
('rim', 60): 1,
('spoke', ...): 1,
('hub', ...): 1
}): 2,
('frame', ...): 1
})
]
通过将'wheel'
替换为('wheel', {'rim': 1, 'spoke': 1, 'hub': 1})
等,
将此树格式修改为所需的输出
Munge this tree format into the desired output
这篇关于如何在Python中将列表转换为树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文