リストのディープコピー

30分プログラム、その613。リストのディープコピーをやってみる。
みんな、Pythonでリストをコピーするには、どうしたらいいか知ってる?

map(None,L)

って書くんだよ。
mapを使うとこは、すんなり理解できるけど、まさか恒等関数の代わりにNoneを使うとは! おそるべし、Python、と思った記憶があります。

でも、このコピーは浅いコピー(shallow copy)です。というわけで、深いコピー(deep copy)を定義してみよう。

使い方

x = [1,[2,3]]
y = deep_dup(x)

x[0] = '*'
x[1][0] = "***"

print x # ['*',['***',3]]
print y # [1,2,3]

ソースコード

#! /usr/bin/python
# -*- mode:python; coding:utf-8 -*-
#
# dup.py -
#
# Copyright(C) 2009 by mzp
# Author: MIZUNO Hiroki / mzpppp at gmail dot com
# http://howdyworld.org
#
# Timestamp: 2009/06/29 21:38:06
#
# This program is free software; you can redistribute it and/or
# modify it under MIT Lincence.
#

def deep_dup(L):
    if '__iter__' in dir(L):
        return map(deep_dup,L)
    else:
        return L

x = [1,[2,3]]
y = deep_dup(x)
x[0] = '*'
x[1][0] = "***"
print x
print y