Python初学教程:元组 使用示例,python示例,python 元组 使用


python 元组 使用示例

#!/usr/bin/python# python 中元组是不可变的序列,和list很像a = 5, 9, 'frank', 33b = ('this', 'that', 'the other')print "A:", a, b# 元组可以相加c = a + bprint "B:", cprint "C:", a[2], c[3:]# 通过下面赋值语句b元组的三个元素分别赋值给了w,x,yw, x, y = bprint "D:", w, x, ytry:    print "E", len(c)    (p, q, s, f) = c    print "F:", p, q, s, fexcept ValueError, descr:    print "*** That won't work:", descr, "***"(p, q, s, f) = c[:4]print "G:", p, q, s, f# 元组中允许包含元组mrbig = (5, 17, 4, ('mac', 'alex', 'sally'), 888, b)print "H:", mrbig# 空元组是合法的,但是是一种坏味道mt = ()singleton = (5,)print "I:", mt, singleton# 元组是不可变的,给元组元素赋值是不允许的try:    fred = 5, 9, 22    fred[1] = 3    print "Won't see this."except TypeError, descr:    print "*** That won't work:", descr, "***"# 元组可以包含listfred = (5, 9, [3, 4, 7])print "J:", fredfred[2][1] = 'cow'print "K:", fred

Python的元组和list非常相似。 但是元组是不可变的。如果元组中仅包含一个元素,最好在元素的后面加一个逗号,例如:(3,)这样写可以避免和函数调用相混淆

评论关闭