zoukankan      html  css  js  c++  java
  • python 拷贝

    copy — Shallow and deep copy operations

      Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other. This module provides generic shallow and deep copy operations (explained below).

        Python中的赋值都是传引用,也就是赋值后两个值都是指向同一个对象。

        如果想要一份独立的拷贝,需要用到copy模块:

    Interface summary:
    
    copy.copy(x)         Return a shallow copy of x.
    copy.deepcopy(x)      Return a deep copy of x.
    exception copy.error   Raised for module specific errors.

        在自己实现的类中可以通过实现__copy__() , __deepcopy__()来定制copy。

        对于list,map和set有简单的拷贝方式:

    Shallow copies of dictionaries can be made using dict.copy(), and of lists by assigning a slice of the entire list, for example,copied_list = original_list[:]. 

    dict.copy()

    set.copy()

    list[:]   

      To change a sequence you are iterating over while inside the loop (for example to duplicate certain items), it is recommended that you first make a copy. Looping over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:

      如果在遍历容器的同时有对容器进行操作,那一定记得使用拷贝

    >>> words = ['cat', 'window', 'defenestrate']
    >>> for w in words[:]:  # Loop over a slice copy of the entire list.
    ...     if len(w) > 6:
    ...         words.insert(0, w)
    ...
    >>> words
    ['defenestrate', 'cat', 'window', 'defenestrate']
  • 相关阅读:
    洛谷P5173 传球(暴力)
    uoj#402. 【CTSC2018】混合果汁(主席树+二分)
    uoj#401. 【CTSC2018】青蕈领主(分治FFT)
    uoj#400. 【CTSC2018】暴力写挂(边分治)
    uoj#399. 【CTSC2018】假面(概率期望)
    P4769 [NOI2018]冒泡排序(dp)
    洛谷P3688/uoj#291. [ZJOI2017]树状数组
    uoj#290. 【ZJOI2017】仙人掌(数数+仙人掌+树形dp)
    Git环境部署
    mysql修改密码
  • 原文地址:https://www.cnblogs.com/tangr206/p/3068393.html
Copyright © 2011-2022 走看看