如何在不改变其形状的情况下取消(不平衡)不必要的嵌套列表?(蟒蛇)

Pet*_*r.k 2 python nested-lists

这与我在许多线程中发现的情况完全不同 - 我并不是要将列表设置为平坦但是不需要的级别如下:

[[[3, 3]]] 应该 [3, 3]

[[[3, 4], [3, 3]]]应该是[[3, 4], [3, 3]],但不是[3, 4], [3, 3][3, 4, 3, 3]因为这完全改变了结构.

基本上,我想减少级别,以便len(a_list)在循环中断之前的第一次和第二次迭代中获得相同的结果.但我的想法有点不对劲:

此代码适用于任何其他内容[[3], [4]].Dunno今天有什么不对,因为它昨天有效.需要一些帮助来纠正这个功能.现在它返回[3]但应该保持不变.

# Unlevel list - reduce unnecessary nesting without changing nested lists structure
def unlevelList(l):
    if len(l) > 0 and isinstance(l, list):
        done = True
        while done == True:
            if isinstance(l[0], list):
                if len(l) == len(l[0]):
                    l = l[0]
                else:
                    l = l[0]
                    done = False
            else:
                done = False
        return l
    else:
        return l
Run Code Online (Sandbox Code Playgroud)

Kev*_*vin 6

我倾向于使用递归来执行此操作:如果对象是长度为1的列表,则剥离外层; 然后,递归地解除其所有孩子的不平等.

def unlevel(obj):
    while isinstance(obj, list) and len(obj) == 1:
        obj = obj[0]
    if isinstance(obj, list):
        return [unlevel(item) for item in obj]
    else:
        return obj

test_cases = [
    [[[3, 3]]],
    [[[3, 4], [3, 3]]],
    [[3], [4]],
    [[[3]]],
    [[[3], [3, 3]]]
]

for x in test_cases:
    print("When {} is unleveled, it becomes {}".format(x, unlevel(x)))
Run Code Online (Sandbox Code Playgroud)

结果:

When [[[3, 3]]] is unleveled, it becomes [3, 3]
When [[[3, 4], [3, 3]]] is unleveled, it becomes [[3, 4], [3, 3]]
When [[3], [4]] is unleveled, it becomes [3, 4]
When [[[3]]] is unleveled, it becomes 3
When [[[3], [3, 3]]] is unleveled, it becomes [3, [3, 3]]
Run Code Online (Sandbox Code Playgroud)

编辑:再次阅读你的问题,我想也许你想[[3], [4]]留下来[[3], [4]].如果是这种情况,那么我将要求解释为"仅剥离顶层的多余括号;保留内部单元素列表不受影响".在这种情况下,您不需要递归.只需剥离顶部列表,直到你再也不能,然后返回它.

def unlevel(obj):
    while isinstance(obj, list) and len(obj) == 1:
        obj = obj[0]
    return obj

test_cases = [
    [[[3, 3]]],
    [[[3, 4], [3, 3]]],
    [[3], [4]],
    [[[3]]],
    [[[3], [3, 3]]]
]

for x in test_cases:
    print("When {} is unleveled, it becomes {}".format(x, unlevel(x)))
Run Code Online (Sandbox Code Playgroud)

结果:

When [[[3, 3]]] is unleveled, it becomes [3, 3]
When [[[3, 4], [3, 3]]] is unleveled, it becomes [[3, 4], [3, 3]]
When [[3], [4]] is unleveled, it becomes [[3], [4]]
When [[[3]]] is unleveled, it becomes 3
When [[[3], [3, 3]]] is unleveled, it becomes [[3], [3, 3]]
Run Code Online (Sandbox Code Playgroud)