当前位置:编程学习 > 网站相关 >>

python 系统学习笔记---元组

元组
元组和列表十分类似,只不过元组和字符串一样是 不可变的  即你不能修改元组。元组通过圆括号中用逗号
分割的项目定义。元组通常用在使语句或用户定义的函数能够安全地采用一组值的时候,即被使用的元组
的值不会改变。
使用元组
#元组由不同的元素组成,每个元素可以存储不同类型的数据,例如   字符串、数字和元组   
#元组通常代表一行数据,而元组中的元素则代表不同的数据项   
创建元组,不定长,但一旦创建后则不能修改长度     
空元组   tuple_name = ()  
#如果创建的元组只有一个元素,那么该元素后面的逗号是不可忽略的  (1,)
#不可修改元素   
>>> user=(1,2,3)  
>>> user[0]=2  
  
Traceback (most recent call last):  
  File "<pyshell#5>", line 1, in <module>  
    user[0]=2  
TypeError: 'tuple' object does not support item assignment 
 
 
[python]  
test=(1,2,3,4)  
print test  
test=(test,5)  
print test  
#元组支持+和切片操作   
test= test[:1][0]   
print test  
#print type(test)  
print dir(tuple)  
  
add=(5,)  
test=test+add  
print test  
  
#去重  
print set((2,2,3,4,4))  
  
#解包     
test = (1,2,3)    
a,b,c = test  
print a,b,c  
  
#遍历  
for elem in test:  
    print elem  
  
for item in range(len(test)):  
    print test[item]  
  
#二元遍历  
test=((1,2),(3,4),(5,6))  
for elem in test:  
    for item in elem:  
        print item  
 
 
 
习题www.zzzyk.com
 #求序列类型的最大元素和最小元素
#入口 :  序列类型List
#返回 : ( 最大元素, 最小元素 ) 应用元组
 
sample
[python] 
def hello():  
    return 'hello','world'  
print hello()  
 
 
补充:Web开发 , Python ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,