本文介绍了如何展平一个2深列表,返回一个列表,其中不包含任何子列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一种拉平"列表的算法,实际上是删除列表中的所有子列表.

I was working on an algorithm that 'flattens' a list, essentially removing any sublists within a list.

例如,[2,3,[3,4]]应该变为[2,3,3,4].我写了以下代码来做到这一点:

For example, [2, 3, [3, 4]] should become [2, 3, 3, 4]. I wrote the following to do this:

def flatten(l):
    total = []
    for i in l:
       if i == int:
           total.append(i)
       elif i == list:
           for j in i:
               total.append(j):
    return total

但是,此算法会产生错误.如果有人可以帮助,那将是很好.另外,如果有人可以显示递归路径来解决此问题,以便可以平铺任意深度"列表(我目前的算法只能平展2D数组)

This algorithm yields an error, however. If someone could help that would be great. Also, if someone could show a recursive path to solve this problem so that lists of arbitrary 'depth' can be flattened (my current algorithm can only flatten a 2D array)

推荐答案

这里有两个主要问题-首先,您没有正确检查商品的类型(应使用 isinstace )其次,您不是递归地调用该函数:

There are two major issues here - first, you aren't checking the type of the item correctly (you should use isinstace) and second you aren't calling the function recursively:

def flatten(l):
    total = []
    for i in l:
       if isinstance(i, list):
           total.extend(flatten(i))
       else:
           total.append(i)

    return total

这篇关于如何展平一个2深列表,返回一个列表,其中不包含任何子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 18:42