我创建了一个遍历任何dict
/ list
混合数据结构的函数,并使用递归进行打印(因为它更有效,更有趣)。问题在于,一旦调用,它将破坏其参数变量。
不仅是参数变量,还有其他任何父子结构:
Father variable: Son = Father
Son variable: InheritSonSecondLevel = Son
如果我以Func(Son)
或Func(Father)
或Func(InheritSonSecondLevel)
的形式调用函数,则所有结构内容都会被破坏。我没有什么可以尝试的。
我正在使用这种混合数据结构。
让我们称之为:混合动力。
这是在for
内部。
hybrid = functionX()
由于printRecursiveDictionary()
将杀死我的内容,因此在结尾处称呼它。
并根据混合内容创建list
。就像是:
fullContent=fullContent+[["A Label",hybrid]]
然后调用printRecursiveDictionary()
。 for
结尾,我用fullContent()
做某事。然后,令人惊讶的是,只剩下一个带有标签和空字典的矩阵。
def printRecursiveDictionary(dictionary,deepness=0):
if(isinstance(dictionary,list) and dictionary!=[]):
if(isinstance(dictionary[0],dict) or
isinstance(dictionary[0],list)):
print("A")
printRecursiveDictionary(dictionary[0],deepness+1)
else:
print("B")
print("\t"*deepness,dictionary[0])
printRecursiveDictionary(dictionary[1:],deepness)
elif(isinstance(dictionary,dict) and dictionary!={}):
if(isinstance(list(dictionary.values())[0],dict) or
isinstance(list(dictionary.values())[0],list)):
print("C")
print("\t"*deepness+str(list(dictionary.keys())[0]))
printRecursiveDictionary(
list(dictionary.values())[0],
deepness+1
)
else:
print("D")
print("\t"*deepness+str(list(dictionary.keys())[0])+":"+str(list(dictionary.values())[0]))
dictionary.pop(list(dictionary.keys())[0])
printRecursiveDictionary(dictionary,deepness)
x=[0,{1:1,2:2,3:3}]
print(x)
y = x
print(y)
printRecursiveDictionary(y)
print(y)
print(x)
结果将是:
[0, {1: 1, 2: 2, 3: 3}]
[0, {1: 1, 2: 2, 3: 3}]
B
0
A
D
1:1
D
2:2
D
3:3
[0, {}]
[0, {}]
答案 0 :(得分:0)
问题在于,一旦调用它就会破坏参数 变量。
以下是printRecursiveDictionary()
的重做,不会破坏其参数。这段代码假设使用Python 3,如果您需要Python 2,请留下评论,我将提供对旧版本的修改:
def printRecursiveDictionary(dictionary, deepness=0):
if isinstance(dictionary, list) and dictionary:
if isinstance(dictionary[0], (dict, list)):
print("A")
printRecursiveDictionary(dictionary[0], deepness + 1)
else:
print("B")
print("\t" * deepness, dictionary[0])
printRecursiveDictionary(dictionary[1:], deepness)
elif isinstance(dictionary, dict) and dictionary:
(key, value), *remainder = dictionary.items()
if isinstance(value, (dict, list)):
print("C")
print("\t" * deepness, key)
printRecursiveDictionary(value, deepness + 1)
else:
print("D")
print("\t" * deepness, str(key) + ":" + str(value))
printRecursiveDictionary(dict(remainder), deepness)
x = [0, {1:1, 2:2, 3:3}]
y = x
print('x:', x)
print('y:', y)
printRecursiveDictionary(y)
print('x:', x)
print('y:', y)
输出
> python3 test.py
x: [0, {1: 1, 2: 2, 3: 3}]
y: [0, {1: 1, 2: 2, 3: 3}]
B
0
A
D
1:1
D
2:2
D
3:3
x: [0, {1: 1, 2: 2, 3: 3}]
y: [0, {1: 1, 2: 2, 3: 3}]
>