2.1.7可变类型与不可变类型
来源:互联网 发布:sim800传输数据 编辑:程序博客网 时间:2024/05/23 11:22
Python有两种内置的或是已经定义过的类型。
可变类型是指那些内容允许实时变更的,典型的可变类型是列表和字典:所有的列表(List)都有可变的方法比如list.append() or list.pop(),并且可以在适当的地方更改。字典和列表拥有一样的特点。
不可变类型不提供变更内容的方法。比如,变量x被置为6,它没有增长的方法。如果你需要加1,你需要创建一个新的对象。
my_list = [1,2,3]
my_list[0]= 4
printmy_list # [4, 2, 3] <- The same list as changed
x=6
x=x+1#Thenewxisanotherobject
这种区别的结果之一就是可变类型不是稳定的,因此它们不能作为字典的key。
对可变的对象使用可变类型,对不可变的对象使用不可变类型,有助于澄清代码的意图。
例如,不可变的列表对应的就是元组。创建一个(1,2)的元组。元组创建以后就不能再更改,并且可以作为字典的键。
让新手较为惊讶的Python的特点之一是 string是种不可变的数据类型。这意味着连接一个string的各个部分时,构造一个可变的list将会使比较效率的做法,然后用join方法把各个部分粘合在一起。需要注意的是,列表生成器比循环调用append()方法要更加的效率。
Bad
# create a concatenated string from 0 to 19 (e.g. "012..1819")
nums =""
forn inrange(20):
nums +=str(n)# slow and inefficient
printnums
Good
# create a concatenated string from 0 to 19 (e.g. "012..1819")
nums =[]
forn inrange(20):
nums.append(str(n))
print"".join(nums)# much more efficient
Best
# create a concatenated string from 0 to 19 (e.g. "012..1819")
nums =[str(n)forn inrange(20)]
print"".join(nums)
foo = ’foo’bar = ’bar’
foobar =foo +bar # This is good
foo +=’ooo’# This is bad, instead you should do:foo=’’.join([foo,’ooo’])
注意:除了join方法你也可以用格式化字符串来连接定义好的字符串,但是在Python3中%操作符将会被str.format()替代。
foo = ’foo’bar = ’bar’
foobar =’%s%s’%(foo,bar)# It is OK
foobar =’{0}{1}’.format(foo,bar)# It is better
foobar =’{foo}{bar}’.format(foo=foo,bar=bar)# It is best
2.1.8 Vendorizing Dependencies
2.1.9 Runners
2.1.10 Further Reading
• http://docs.python.org/2/library/
• http://www.diveintopython.net/toc/index.html
- 2.1.7可变类型与不可变类型
- python可变类型与不可变类型
- python 可变 与 不可变类型
- python中的可变与不可变类型
- Python函数之可变类型与不可变类型
- Python的可变类型与不可变类型
- Python的可变类型与不可变类型
- python 可变不可变类型
- 可变类型和不可变类型
- Python探索记(16)——Python的可变类型与不可变类型
- java中可变类型和不可变类型
- Java中可变类型和不可变类型
- python的可变类型和不可变类型
- Python 引用 :可变类型和不可变类型
- 可变与不可变
- 不可变类型
- python类的可变类型成员和不可变类型成员的区别
- python 列表去重(不可变类型和可变类型)
- Android游戏开发之旅View类详解自定义View的常用方法
- VS2008下直接安装使用Boost库1.46.1版本
- 用C#垂直调整Kinect马达的的仰角
- iOS开发学习路径的一些建议
- iOS OpenSSL 编译
- 2.1.7可变类型与不可变类型
- iOS中浅拷贝和深拷贝的区别
- ReentrantLock和synchronized两种锁定机制的对比
- java 反射机制详解
- 浅谈算法和数据结构(3):合并排序
- zoj3734
- Oracle 12c agent install for linux
- VS2010x64 无法启动此程序,因为计算机中丢失MSVCR100D.dll和LINK : fatal error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏
- 猪八ms