且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从Python的嵌套列表中提取字符串

更新时间:2022-06-22 22:45:21

通常,当您必须处理任意级别的嵌套时,递归解决方案是一个不错的选择.列表中的列表,解析HTML(标签中的标签),使用文件系统(目录中的目录)等.

In general, when you have to deal with arbitrary levels of nesting, a recursive solution is a good fit. Lists within lists, parsing HTML (tags within tags), working with filesystems (directories within directories), etc.

我尚未对该代码进行广泛的测试,但我相信它应该可以执行您想要的操作:

I haven't tested this code extensively, but I believe it should do what you want:

ll = [ 1, 2, 3, [4, 5, [6, 7, 8]]]

def flatten(input_list):
    output_list = []
    for element in input_list:
        if type(element) == list:
            output_list.extend(flatten(element))
        else:
            output_list.append(element)
    return output_list

print (flatten(ll)) #prints [1, 2, 3, 4, 5, 6, 7, 8]

通常,递归很容易考虑,解决方案往往非常优雅(如上),但是对于真正非常嵌套的东西(想想成千上万个级别),您可能会遇到栈溢出等问题.

In general recursion is very easy to think about and the solutions tend to be very elegant (like above) but for really, really deeply nested things - think thousands of levels deep - you can run into problems like stack overflow.

通常这不是问题,但是我相信递归函数始终可以*转换为循环(看起来并不那么好.)

Generally this isn't a problem, but I believe a recursive function can always* be converted to a loop (it just doesn't look as nice.)

  • 注意:在这里,我对compsci理论并不感到热衷.如果我输入错误,可以添加详细信息或纠正我.