私はバイナリツリーのコードの次のスニペットを試し、arrと文字列を後で印刷しようとすると、正しい結果が得られますが、文字列は空です。何かご意見は?参照によって渡されるリストや値渡される文字列とは何か関係がありますか?Pythonの文字列対リストの奇妙な動作
def post_order(root, arr = []):
if(root is not None):
post_order(root.left, arr)
post_order(root.right, arr)
arr.append(root.value)
def post_order1(root, string = ''):
if(root is not None):
post_order1(root.left, string)
post_order1(root.right, string)
string += str(root.value)
# assume I've made my binary tree
arr, string = [], ''
post_order(root, arr)
post_order1(root, string)
print arr, string
# arr holds the correct post-order sequence
# string is empty
文字列は、文字列+ = 'ので不変ですstr(root.value) 'は多分やっていないかもしれません、新しい文字列を渡してそれを返すpost_order1を呼び出す前に+ =を意味しますか?私はあなたが文字列を属性にするクラスでうまくいくかもしれないと思う。 –
関連:[Pythonでは、呼び出し元によって認識されるように関数がいくつかの引数を変更できるのはなぜですか?](http://stackoverflow.com/q/575196/4279) – jfs
あなたは十分な情報を含んでいません。入力、希望および既存の出力を含めます。また、これらの関数を実際に返すことで、変数がガベージコレクトされるようにする必要があります。 – Pouria