如何在嵌套列表的每个子列表中指定特定元素的索引?

Ed *_*d Z 8 python function list python-3.x

我有几个嵌套列表,它们在子列表中都是彼此置换的:

x = [
['a', [['b', 'c', [['e', 'd']]]]],
['a', [['b', [['e', 'd']], 'c']]],
[[['b', 'c', [['e', 'd']]]], 'a'],
['a', [[[['d', 'e']], 'c', 'b']]], 
['a', [['b', [['d', 'e']], 'c']]]
]
Run Code Online (Sandbox Code Playgroud)

我只想选择那些符合此要求的元素:如果子列表中包含元素“ d”或“ b”,则该子列表中的索引必须为0。因此,仅在x中的列表中

['a', [['b', [['d', 'e']], 'c']]]
Run Code Online (Sandbox Code Playgroud)

必须选择,因为'd'在其子列表中具有索引0,同时'b'在其子列表中具有索引0。我试过这个功能:

def limitation(root, nested):
    result = []
    for i in nested:
        if isinstance(i, list):
            return limitation(root, i)
        else:
            if (i in ['d', 'b']  and nested.index(i) == 0):
                return root
for i in x:
    print(limitation(i, i))
Run Code Online (Sandbox Code Playgroud)

但是输出是这样的:

['a', [['b', 'c', [['e', 'd']]]]]
['a', [['b', [['e', 'd']], 'c']]]
[[['b', 'c', [['e', 'd']]]], 'a']
['a', [[[['d', 'e']], 'c', 'b']]]
['a', [['b', [['d', 'e']], 'c']]]
Run Code Online (Sandbox Code Playgroud)

因此,它不认为“ d”和“ b”在子列表中都必须具有索引0。你能帮我解决吗?

Cha*_* DZ 3

如果 asub-list包含'b' or 'd'该元素必须位于第一个索引 [0]中:

x = [
['a', [['b', 'c', [['e', 'd']]]]],
['a', [['b', [['e', 'd']], 'c']]],
[[['b', 'c', [['e', 'd']]]], 'a'],
['a', [[[['d', 'e']], 'c', 'b']]],
['a', [['b', [['d', 'e']], 'c']]]
]


def limitation(nested):
    for index, subelement in enumerate(nested):
        if isinstance(subelement, list):
            if not limitation(subelement):
                return False
        else:
            if subelement in ['d', 'b'] and not index:
                return False
    return True


for element in x:
    if limitation(element):
        print(element)  # ['a', [['b', [['d', 'e']], 'c']]]
Run Code Online (Sandbox Code Playgroud)