如何在python中找到两个结构相同的列表?

Ume*_*cha 5 python recursion list

定义一个带有两个输入的过程same_structure.True如果列表具有相同的结构,则应输出 ,False 否则.在以下情况下,两个值p和q具有相同的结构:

Neither p or q is a list.

Both p and q are lists, they have the same number of elements, and each
element of p has the same structure as the corresponding element of q.
Run Code Online (Sandbox Code Playgroud)

编辑:为了使图片清晰,以下是预期的输出

same_structure([1, 0, 1], [2, 1, 2])
    ---> True
same_structure([1, [0], 1], [2, 5, 3])
    ---> False
same_structure([1, [2, [3, [4, 5]]]], ['a', ['b', ['c', ['d', 'e']]]])
    ---> True
same_structure([1, [2, [3, [4, 5]]]], ['a', ['b', ['c', ['de']]]])
    ---> False 
Run Code Online (Sandbox Code Playgroud)

我认为递归最好在python中解决这个问题我已经提出了以下代码,但它不起作用.

def is_list(p):
    return isinstance(p, list)

 def same_structure(a,b):
    if not is_list(a) and not is_list(b):
        return True
    elif is_list(a) and is_list(b):
        if len(a) == len(b):
            same_structure(a[1:],b[1:])
    else:
        return False
Run Code Online (Sandbox Code Playgroud)

Ósc*_*pez 5

你错过了一个案子,在第二个案件中忘了回来.请注意,没有必要明确地比较列表的长度,因为第一种情况负责这一点 - 如果其中一个列表为空而另一个列表不是,那是因为一个列表的元素少于另一个列表:

def same_structure(a, b):
    if a == [] or b == []:  # one of the lists is empty
        return a == b       # are both of the lists empty?
    elif is_list(a[0]) != is_list(b[0]):
        return False        # one of the elements is a list and the other is not
    elif not is_list(a[0]): # neither element is a list
        return same_structure(a[1:], b[1:])
    else:                   # both elements are lists
        return same_structure(a[0], b[0]) and same_structure(a[1:], b[1:])
Run Code Online (Sandbox Code Playgroud)


okm*_*okm 5

而不是same_structure(a[1:],b[1:]),您需要逐个检查a和b的项目对

def is_list(p):
    return isinstance(p, list)

def same_structure(a, b):
    if not is_list(a) and not is_list(b):
        return True
    elif (is_list(a) and is_list(b)) and (len(a) == len(b)):
        return all(map(same_structure, a, b)) # Here
    return False
Run Code Online (Sandbox Code Playgroud)


Jac*_*cob 3

递归一个好主意,但不是您建议的方式。首先(这可能只是一个拼写错误),您实际上并没有在这里返回任何内容:

if len(a) == len(b):
    same_structure(a[1:],b[1:])
Run Code Online (Sandbox Code Playgroud)

其次,您应该递归地处理每个元素,而不是每个子列表。IE。:

if len(a) == len(b):
    for i in range(len(a)):
        if not same_structure(a[i], b[i]):
            return False
    return True
else:
    return False
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。