简体   繁体   English

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

[英]How to find out two lists with same structure in python?

Define a procedure, same_structure, that takes two inputs.定义一个过程,same_structure,接受两个输入。 It should output True if the lists have the same structure, and False otherwise.如果列表具有相同的结构,则它应该为 output True ,否则为False Two values, p and q have the same structure if:如果满足以下条件,则两个值 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.

EDIT: To make the picture clear the following are the expected output编辑:为了使图片清晰,以下是预期的 output

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 

I thought recursion would be best to solve this problem in python I have come up with the following code but its not working.我认为递归最好在 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

Instead of same_structure(a[1:],b[1:]) , you need to check item pair of a and b one by one而不是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

You're missing one case, and forgot to return in the second case.您遗漏了一个案例,而在第二个案例中忘记返回。 Notice that is not necessary to explicitly compare the lengths of the lists, as the first case takes care of this - if one of the lists is empty and the other not, it's because one list had fewer elements than the other:请注意,没有必要明确比较列表的长度,因为第一种情况会处理这个问题——如果一个列表为空而另一个不为空,那是因为一个列表的元素比另一个少:

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:])

Recursion would be a good idea, but not the way you've suggested it.递归个好主意,但不是你建议的那样。 First off (and this may be only a typo), you don't actually return anything here:首先(这可能只是一个错字),你实际上并没有在这里返回任何东西:

if len(a) == len(b):
    same_structure(a[1:],b[1:])

Second, you should recursively deal with each element, not each sublist.其次,你应该递归地处理每个元素,而不是每个子列表。 ie.: 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

Hope this helps.希望这可以帮助。

Since the specification says that the input are two lists, you can iterate the lists inside your function without further checks, and only do recursive calls if you encounter sublists:由于规范说明输入是两个列表,因此您可以在 function 中迭代列表而无需进一步检查,并且仅在遇到子列表时才进行递归调用:

def same_structure(a, b):
    if len(a) != len(b):
        return False
    return all(is_list(x) and is_list(y) and same_structure(x, y) or
               not is_list(x) and not is_list(y)
               for x, y in zip(a, b))

You can try this way too also, check the type of both lists & length of both lists and do this recursively for sub-lists of both list.您也可以尝试这种方式,检查两个列表的类型和两个列表的长度,并对两个列表的子列表递归执行此操作。

def same_structure(a,b):
    return isinstance(a, list) and isinstance(b, list) and len(a) == len(b)  
    and all(same_structure_as(c, d) for c, d in zip(a, b) if isinstance(c, list))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM