定義一個過程,same_structure,需要兩個輸入。如果列表具有相同的結構,則應該輸出 True
,否則應該輸出False
。兩個值,p和q具有相同的結構,如果:如何找出兩個python中具有相同結構的列表?
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.
編輯:爲了使畫面清晰,以下是預期輸出
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
我想遞歸將是最好的解決這個問題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
@SvenMarnach:除非我誤讀的問題,[2,(3,4)]和[2,(5)具有相同的結構:他們是兩個列表,它們具有相同的元素的數量,並且p的每個元素都具有與q的對應元素相同的結構,因爲它們都不是列表。 IOW它只是重要的列表結構,值不會(因此[2]和[3]也具有相同的結構。) – DSM 2012-04-09 15:20:33
爲列表定義「相同的結構」,與python ['a','1 ']不等於['1','a']。也許你會更好地使用集合。 – KurzedMetal 2012-04-09 15:24:20
在這種情況下,儘管我認爲我*會*說他們包含相同的元素,其中的平等是由給定的關係定義的。我想我自己在這一天有過這樣的問題。 – DSM 2012-04-09 15:37:54