python通过引用传递

时间:2017-12-10 01:20:49

标签: python parameter-passing depth-first-search

我知道Python正在使用"通过引用传递"。然而,当我被困在一个小时的小时里,我觉得我仍然不明白事情是怎么发生的。下面是我的代码,它使用深度优先搜索来实现列出集合的所有子集。

def subset_of_unique_dfs(mylist):
"""
:param list: a list of char first assuming the element in the list is unique
:return: list of subset of the input list
we could treated as tree, with ith level represent the ith element is selected or not (binary tree)
when we reach the leafnode of the tree, append the result
so we need to track the level of the tree where we currently at
"""
result_list = []
def helper(thelist, level, curList,result):
    print("at level ",level, "curResult is ",curList)
    if level == len(thelist):
        print type(curList)
        result.append(curList)
        return
    curList.append(thelist[level])
    helper(thelist,level + 1,curList,result)
    curList.pop()
    helper(thelist,level + 1,curList,result)

helper(mylist, 0, [],result_list)
return result_list

print subset_of_unique_dfs(['a','b','c'])
"""
[[], [], [], [], [], [], [], []]
"""

我一直在努力争取一个空列表。然后我试着改变" result.append(curList)" to" result.append(list(curList))",返回正确的结果。我可以问一下应用list(curList)会发生什么吗?我曾经把result.append(curList)作为将与curList绑定的对象附加到result。例如,下面的测试用例实际上显示append(listA)和append(list(listA))之间没有区别

tmp1 = [[1,2],[2,3]]
tmp1_1 = [[1,2],[2,3]]
tmp2 = [3,4]
tmp1.append(tmp2)
tmp1_1.append(list(tmp2))
print tmp1
print tmp1_1
"""
[[1, 2], [2, 3], [3, 4]]
[[1, 2], [2, 3], [3, 4]]
"""

1 个答案:

答案 0 :(得分:2)

列表(tmp2)的输出等于测试用例中tmp2的输出,它的工作原理如下:

tmp1 = [[1,2],[2,3]]
tmp1_1 = [[1,2],[2,3]]
tmp2 = [3,4]
tmp1.append(tmp2)
tmp1_1.append([tmp2])
print tmp1
print tmp1_1
"""
[[1, 2], [2, 3], [3, 4]]
[[1, 2], [2, 3], [[3, 4]]]
"""