2017-12-10 22 views
0

私はPythonが「参照渡し」によって動作していることを知っています。しかし、私が何時間もバグに追い込まれたとき、私は何が起こったのかまだ分かりませんでした。以下は私のコードであり、セットのすべてのサブセットのリストを実装するために深い最初の検索を使用しています。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)"を "result.append(list(curList))"に変更しようとすると、正しい結果が返されます。 list(curList)を適用して何が起こったのか尋ねてもいいですか?私はresult.append(curList)を使用して、結果をcurListでバインドするオブジェクトを追加していました。例えば、以下のテストケースは、実際にアペンド(リスタ)との間の差を示さなかったし、追加(リスト(リスタ))

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]] 
""" 
+0

Pythonは「参照渡し」(「値渡し」もありません)であり、あなたが思っている限り理解できません。 「オブジェクトを渡す」はおそらく最善の記述です。 –

+0

私は同様の質問を見つけました。(https://stackoverflow.com/questions/45335809/python-pass-by-reference-and-slice-assignment)しかし、まだ理解するのは少し難しいです。同じパスへの多くの参照のリスト、最終的には無駄になります。私は実際にそれが別のオブジェクト(パス)のために同じリファレンスであると思っていました。それは、appendとpopで修正されています...そして、私はさらに「何も減らされていません」と混乱します。 (https://stackoverflow.com/users/2069064/barry) – evehsu

+0

@TerryJanReedy:「値渡し」もありません。Pythonでの渡しと代入のセマンティクスはJavaのものと同じですが、Javaは一般的にパスバイと呼ばれていますこのサイトの - 値 – newacct

答えて

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]]] 
""" 
+0

あなたの答えをありがとう。あなたはtmp2の参照を追加するのではなく、実際にtmp1.append(tmp2)がtmp2の名前にバインディングするオブジェクトを実際に追加することを明確にするために私を助けますか?なぜ私の関数に戻ったときにresult.append(curList)リファレンス? – evehsu