python - 根据二叉树逐级制作嵌套列表
问题描述
使用二叉树,我试图逐级制作嵌套列表。这是我所做的:
arrows = [("modifier","adverb1"),("noun","modifier"),("verb","noun"),("verb","adverb2"),("root","verb")]
dom_list = list(dict.fromkeys([a[0] for a in arrows]))
dom_list.pop()
depth = []
for a in dom_list:
MC = [v[1] for v in arrows if v[0] == a]
depth.append(MC)
con = []
for i in range(len(dom_list)):
c = [dom_list[i], depth[i]]
con.append(c)
代码行导致:
[['modifier', ['adverb1']],
['noun', ['modifier']],
['verb', ['noun', 'adverb2']]]
我想用这个输入做一个嵌套列表,如:
['root', ['verb', ['noun', ['modifier', ['adverb1']], 'adverb2']]]
有没有办法做到这一点?任何帮助将不胜感激。
解决方案
当然不是我最优化的代码,但它适用于您提供的数据,因为我了解您的问题。也许这可以帮助您找出更优雅的解决方案:
def flat_gen(x):
# Flattens a nested list, taken from here but forgot the post
def iselement(e):
return not(isinstance(e, collections.Iterable) and not isinstance(e, str))
for el in x:
if iselement(el):
yield el
else:
yield from flat_gen(el)
tmp = [list(x) for x in arrows]
tmp_new = []
for a in tmp:
for b in tmp:
if b[1] == a[0]:
b[1] = a
tmp_new.append(b)
else:
tmp_new.append(b)
# Find longest chain
idx_longest = [len(list(flat_gen(e))) for e in tmp_new].index(max([len(list(flat_gen(e))) for e in tmp_new]))
longest = tmp_new[idx_longest]
# Identify missing elements in longest chain
missing = set(flat_gen(arrows)).difference(list(set(flat_gen(longest))))
for m in missing:
for a in arrows:
if m in a:
outer = [""]
i = 0
outer[i] = longest
found = False
while not found:
print(a[0])
print(outer[i])
inner = outer[i][1]
if outer[i][0] == a[0]:
# Found position where to insert
outer[i].append(a[1])
found = True
else:
# Continue searching
outer.append(inner)
i += 1
a = list(a)
a[1] = outer[i]
print(a)
回报:
['root', ['verb', ['noun', ['modifier', 'adverb1']], 'adverb2']]
推荐阅读
- function - 这个递归柯里化函数有什么问题
- generics - F# 中 OCaml 样式的泛型类型参数的语法是什么?
- javascript - 为什么即使上传的文件路径没有存储在数据库中,我也会得到 200?
- c# - 无法使下拉列表可搜索
- html - 如何强制 ag-grid 占据页面的其余部分?
- html - 如何将重叠的列表项放在一起?
- ruby-on-rails - Rails - 在有或没有引发错误的情况下保存模型
- reactjs - React Hooks State 只更新一次 Type:error not a function
- jpa - Spring Data JPA 方法在限制 ResultSet 时抛出 'org.springframework.dao.InvalidDataAccessResourceUsageException' 异常
- php - 如何为每个用户计算收到的通知计数