2017-02-02 18 views
0

私はリストのリストをいくつか持っていて、コード全体を通してリスト内の項目を編集し、後ですべてを初期値に戻したいと考えています。ここでPythonはリスト内の項目を初期値にリセットします

は例です:

list_a = [0, 1, 2] 
list_b = [list_a, 3, 4] 
list_c = [6, 7] 
list_d = [8, 9] 
lists = [0, list_b, 5, list_c, list_d] 
#As you can see, lists are of varying length, and sometimes nested multiple times. 

print(lists) 
Out>>> [0, [[0, 1, 2], 3, 4], 5, [6, 7], [8, 9]] 

#Currently, I'm saving the important items of "lists" in the first item, like this: 
lists[0] = lists[1:] 

#Then I edit the values of various items, like this: 
lists[1][0][2] = 0 
lists[2] = 0 
lists[3][1] = 0 
lists[4][1] = 0 

print(lists[1:]) 
Out>>> [[[0, 1, 0], 3, 4], 0, [6, 0], [8, 0]] 

#Then I try to reset those values to the originals that I stored in lists[0] 
lists[1:] = lists[0] 

print(lists[1:]) 
Out>>> [[[0, 1, 0], 3, 4], 5, [6, 0], [8, 0]] 

あなたが見ることができるように、この方法は、リストのために働く[2]という項目が値ではなく、ネストされたリストであるため。リスト[0]でコピーを作成するのに[1:]を使用しても、ネストされたリストへの参照はコピーされたもので、そのネストされたリストの値ではないようです。

リスト[1:]の値をリスト[0]に正しくコピーしてから、同じインデックスを両方のコピーで参照しなくても元に戻すにはどうすればよいですか?

おそらく、リスト内のすべてのアイテムを元の値に戻して、同じ意図した結果を達成する簡単な方法がありますか?

答えて

0

persistent data structuresを使用してください。突然変異を避ければ、より多くの共有が可能になり、このような遠く離れた場所では気まずい行動を避けることができます。例えば

>>> from pyrsistent import pvector 
>>> list_a = pvector([0, 1, 2]) 
>>> list_b = pvector([list_a, 3, 4]) 
>>> list_c = pvector([6, 7]) 
>>> list_d = pvector([8, 9]) 
>>> lists = pvector([0, list_b, 5, list_c, list_d]) 
>>> print(lists) 
pvector([0, pvector([pvector([0, 1, 2]), 3, 4]), 5, pvector([6, 7]), pvector([8, 9])]) 
>>> lists = lists.set(0, lists[1:]) 
>>> lists = lists.transform([1, 0, 2], 0) 
>>> lists = lists.transform([2], 0) 
>>> lists = lists.transform([3, 1], 0) 
>>> lists = lists.transform([4, 1], 0) 
>>> print(lists[1:]) 
pvector([pvector([pvector([0, 1, 0]), 3, 4]), 0, pvector([6, 0]), pvector([8, 0])]) 
>>> lists = lists[:1] + lists[0] 
>>> print(lists[1:]) 
pvector([pvector([pvector([0, 1, 2]), 3, 4]), 5, pvector([6, 7]), pvector([8, 9])]) 
>>> 

はまた、Pythonは非リスト変数を持っています。ランダムな値のリストの最初の要素は、物事を「保存」するための不思議な場所です。上記を踏まえれば、元の値を別の変数に保存することができます。たとえば:

>>> list_a = pvector([0, 1, 2]) 
>>> list_b = pvector([list_a, 3, 4]) 
>>> list_c = pvector([6, 7]) 
>>> list_d = pvector([8, 9]) 
>>> lists = original = pvector([list_b, 5, list_c, list_d]) 

は今、あなたはlistsと周りのネジことができますし、それに飽きたときに、lists = originalはすぐに戻って初期状態にあなたをもたらします。

関連する問題