2012年12月15日 星期六

Python 2.x list 超新手常犯的錯誤

a = [1, 2, 3]
b = a
是將b指向 和a共用的 [1,2,3]
如果b用copy a list value成一個獨立的list,請用
b = list(a)
 
或是用 
copy.deepcopy():
 
  • If the list contains objects and you want to copy them as well, use generic copy.deepcopy():
    import copy
    new_list = copy.deepcopy(old_list)
    Obviously the slowest and most memory-needing method, but sometimes unavoidable.
 
詳參:

Python: copying a list the right way

An Introduction to Python Lists

How to clone a list in python?