hxx800的个人博客分享 http://blog.sciencenet.cn/u/hxx800

博文

关于python的复制对象

已有 6070 次阅读 2012-10-25 23:00 |个人分类:电脑应用|系统分类:科研笔记|关键词:学者| Python, div

一般程序里面复制对象的话可以 

  a=[1,2]
  b=a
但是python里面不行。python里面运行这两行命令之后其实还是a和b指向同一对象
  b[1]=3
>>> print a,b
[1, 3] [1, 3]

这种情况在处理数组和list的时候经常会遇到,如何克服呢?当然有办法,就是标准库中的copy模块!
1. copy.copy 浅拷贝 只拷贝父对象,不会拷贝对象的内部的子对象。
2. copy.deepcopy 深拷贝 拷贝对象及其子对象
一个很好的例子(来自 http://www.jb51.net/article/15714.htm
import copy
= [1234, ['a''b']] #原始对象

= a #赋值,传对象的引用
= copy.copy(a) #对象拷贝,浅拷贝
= copy.deepcopy(a) #对象拷贝,深拷贝

a.append(
5#修改对象a
a[4].append('c'#修改对象a中的['a', 'b']数组对象

print 'a = ', a
print 'b = ', b
print 'c = ', c
print 'd = ', d

输出结果:
a = [1, 2, 3, 4, ['a', 'b', 'c'], 5]
b = [1, 2, 3, 4, ['a', 'b', 'c'], 5]
c = [1, 2, 3, 4, ['a', 'b', 'c']]
d = [1, 2, 3, 4, ['a', 'b']]

另外,刚碰到的一个问题就是如何让一个列表中的数组删除掉呢?如果用下面的语句那你就错了!
    for  file in array:
          if file == "delete": array.remove(file)
这个原因是  当你删除file之后数组位数下降,但是for循环是按照最初的维数循环的。如果细心点你会发现,这个循环会跳过一些元素。这下就不好了。更好的方法是采取这样,这是个实际的例子。只能设置两个数据,然后用append命令,而不是remove!!

tmpaplusfiles=os.listdir(self.datasetsdir)  #improved on Orc25  by xingxing
self.logfile.write("choose directories under "+self.datasetsdir+"( only f***w !!) ====IMPORTANT====")
for file in tmpaplusfiles:
   if (len(file)!=5) or (file[0]!='f') or (file[-1]!='w'):
       print "__"+file+"__ deleted from the band list."
   else:
self.aplusfiles.append(file)
print "__"+file+"__ included ."






https://m.sciencenet.cn/blog-462509-626164.html

上一篇:sci收录的一些常用天文杂志

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-5-20 06:27

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部