【问题标题】:Python parse list into list of listsPython将列表解析为列表列表
【发布时间】:2020-04-19 18:29:10
【问题描述】:

您如何(递归地)根据列表中的某些元素将列表更改为列表列表。例如,我将如何改变

['(', 'hi', 'there', '(', 'how', ' are', '(', 'you', ')', ')', ')']

进入

['hi', 'there', ['how', 'are', ['you']]]

我猜基本的递归函数看起来像

def makelist(l):
    if l[0] != '(':
        return token
    else:
        return makesublist(l[0]) + makelist(l[1:])

makesublist 函数将从每个 '(' 到 ')' 生成子列表

【问题讨论】:

  • 你有没有尝试过reduce?
  • 对不起,我想看看如何在没有导入的情况下做到这一点:)
  • 添加您尝试过但不起作用的代码
  • 我输入了基本结构,但我仍在尝试理解它的递归性质。

标签: python-3.x list parsing recursion


【解决方案1】:

我完全不明白你在做什么,但这样的事情可能会有所帮助

a_list = ['(', 'hi', 'there', '(', 'how', ' are', '(', 'you', ')', ')', ')']

without_empty_strings = []
for string in a_list:
    if string !="(" and string != ")":
        without_empty_strings.append(string)


print(without_empty_strings)

输出是

['hi', 'there', 'how', ' are', 'you']

【讨论】:

  • 所以我需要根据 '(' 和 ')' 的位置创建一个列表列表,所以仅仅创建一个单词列表并没有真正的帮助,因为我要去需要括号的索引。
猜你喜欢
  • 2011-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
相关资源
最近更新 更多