Python数列变量修改我写了段程序,为什么我只想修改数列的一个值,但是每次已修改整列的值都被修改了.程序如下:strategy_do_nothing=['DoNothing']*2strategy = []treatment=['DoNothing','Minor','Major']if len(strate
来源:学生作业帮助网 编辑:作业帮 时间:2024/07/14 12:19:24
![Python数列变量修改我写了段程序,为什么我只想修改数列的一个值,但是每次已修改整列的值都被修改了.程序如下:strategy_do_nothing=['DoNothing']*2strategy = []treatment=['DoNothing','Minor','Major']if len(strate](/uploads/image/z/1842523-43-3.jpg?t=Python%E6%95%B0%E5%88%97%E5%8F%98%E9%87%8F%E4%BF%AE%E6%94%B9%E6%88%91%E5%86%99%E4%BA%86%E6%AE%B5%E7%A8%8B%E5%BA%8F%2C%E4%B8%BA%E4%BB%80%E4%B9%88%E6%88%91%E5%8F%AA%E6%83%B3%E4%BF%AE%E6%94%B9%E6%95%B0%E5%88%97%E7%9A%84%E4%B8%80%E4%B8%AA%E5%80%BC%2C%E4%BD%86%E6%98%AF%E6%AF%8F%E6%AC%A1%E5%B7%B2%E4%BF%AE%E6%94%B9%E6%95%B4%E5%88%97%E7%9A%84%E5%80%BC%E9%83%BD%E8%A2%AB%E4%BF%AE%E6%94%B9%E4%BA%86.%E7%A8%8B%E5%BA%8F%E5%A6%82%E4%B8%8B%EF%BC%9Astrategy_do_nothing%3D%5B%27DoNothing%27%5D%2A2strategy+%3D+%5B%5Dtreatment%3D%5B%27DoNothing%27%2C%27Minor%27%2C%27Major%27%5Dif+len%28strate)
Python数列变量修改我写了段程序,为什么我只想修改数列的一个值,但是每次已修改整列的值都被修改了.程序如下:strategy_do_nothing=['DoNothing']*2strategy = []treatment=['DoNothing','Minor','Major']if len(strate
Python数列变量修改
我写了段程序,为什么我只想修改数列的一个值,但是每次已修改整列的值都被修改了.程序如下:
strategy_do_nothing=['DoNothing']*2
strategy = []
treatment=['DoNothing','Minor','Major']
if len(strategy)
Python数列变量修改我写了段程序,为什么我只想修改数列的一个值,但是每次已修改整列的值都被修改了.程序如下:strategy_do_nothing=['DoNothing']*2strategy = []treatment=['DoNothing','Minor','Major']if len(strate
在Python里面是分为可变对象与不可变对象两类的.
对于你这个问题就是strategy_do_nothing是list,而list是可变对象,所以在strategy.append(strategy_do_nothing)之后,这个strategy里面你每次往里面追加的都是strategy_do_nothing这个对象(注意是这个对象或者说这个可变的变量.而不是['DoNothing']*2这个值),但是在后面的strategy[k][0]=treatment[k]当k = 0时,就是strategy[0][0]=treatment[0],此时strategy的strategy[0][0]就是strategy_do_nothing这个对象,你在这里对他赋值改变了他的值,那么在其他地方用到这个对象的时候也会改掉他的值,所以使得最终所有的strategy_do_nothing的地方都成为同样的东西了.
要解决这个方法:
strategy.append(strategy_do_nothing)改成strategy.append(strategy_do_nothing[:])
或者是用copy.deepcopy,或者Google一下"Python deep copy"、"Python 深拷贝"
PS:不知道你原意是要干嘛,如果要实现这个效果,为何不:
treatment = ['DoNothing','Minor','Major']
strategy_do_nothing = ['DoNothing'] * len(treatment)
strategy = zip(treatment,strategy_do_nothing)
print strategy
PS:你for k in range(len(treatment)):写的实在有点奇葩哈……