python - 创建嵌套/递归列表
问题描述
如何递归创建列表?
我有这个清单:
l = ['a', 'b', 'new', 'c', 'd', 'new', 'z', 'x', 'c', 'fin', 'f', 'fin',
'g', 'l', 'new', 'z', 'x', 'c', 'fin', 'j']
预期的输出是:
r = ['a', 'b', ['c', 'd', ['z', 'x', 'c'] 'f'], 'g', 'l', ['z', 'x', 'c'] 'j']
到目前为止我已经尝试过:
def asd(l, index=0):
r = []
for i in l[index:]:
index += 1
if i == 'new':
i, index = asd(l, index)
r.append(i)
if i == 'fin':
return r
return r, index
r, index = asd(l)
我无法理解如何使它工作。谁能帮我?
解决方案
这是一种非递归解决方案,可以创建您的列表,一次解析,无需任何昂贵的index()
操作:
l = ['a', 'b', 'new', 'c', 'd', 'new', 'f', 'fin', 'g', 'fin', 'j']
rv = []
curr = [rv] # things are always added to the last element if not 'fin' or 'new'
for elem in l:
if elem == "new":
# create a new list, put it at end of curr
curr.append([])
# add that list to the one before
curr[-2].append(curr[-1])
elif elem == "fin":
# done, remove from curr
curr.pop()
else:
curr[-1].append(elem)
print(rv)
输出:
['a', 'b', ['c', 'd', ['f'], 'g'], 'j']
l = ['a', 'b', 'new', '1', '2', '3', 'fin', 'c', 'new', 'x', 'y', 'z', 'fin',]
导致
['a', 'b', ['1', '2', '3'], 'c', ['x', 'y', 'z']]
您需要对不平衡/不正确new
/fin
的情况进行万无一失
在 Matthieu 发表评论后进行了编辑以使其更加简洁。
推荐阅读
- python - 使用google colab将其安装在谷歌驱动器中后无法在pip中找到模块
- grails - GrailsPageFilter 未导入 -Grails 4.xx
- r - 检查目标时出错:预期密集具有二维,但得到数组,但仅在最终模型拟合期间,而不是调整
- javascript - 每次在javascript中执行onkeydown事件时,如何输出打印+1?
- java - Android Studio Emulator 无法正常工作:显示巨大的模拟器
- asp.net-mvc - 如何使用带有 Ajax 的 ASP.Net MVC 在弹出窗口中查看图像?
- ios - 即使从 App Store 更新后,iOS 应用程序也不会更新
- reactjs - React Material UI 手动触发 Select
- kotlin-coroutines - kotlin 协程,定期发出数据并检查订阅者数量
- java - 元组的排列