How to clone or copy a set in Python?

后端 未结 2 1588
忘了有多久
忘了有多久 2020-12-18 17:47

For copying a list: shallow_copy_of_list = old_list[:].

For copying a dict: shallow_copy_of_dict = dict(old_dict).

But for a

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-18 18:26

    Besides the type(x)(x) hack, you can import copy module to make either shallow copy or deep copy:

    In [29]: d={1: [2,3]}
    
    In [30]: sd=copy.copy(d)
        ...: sd[1][0]=321
        ...: print d
    {1: [321, 3]}
    
    In [31]: dd=copy.deepcopy(d)
        ...: dd[1][0]=987
        ...: print dd, d
    {1: [987, 3]} {1: [321, 3]}
    

    From the docstring:

    Definition: copy.copy(x)
    Docstring:
    Shallow copy operation on arbitrary Python objects.
    

提交回复
热议问题