ITeye博客

python 系统学习笔记(六)---元组

lovnet · 2013-03-06 16:41 · Markdown

元组

元组和列表十分类似,只不过元组和字符串一样是 不可变的 即你不能修改元组。元组通过圆括号中用逗号

分割的项目定义。元组通常用在使语句或用户定义的函数能够安全地采用一组值的时候,即被使用的元组

的值不会改变。

使用元组

  1. #元组由不同的元素组成,每个元素可以存储不同类型的数据,例如字符串、数字和元组
  2. #元组通常代表一行数据,而元组中的元素则代表不同的数据项
  3. 创建元组,不定长,但一旦创建后则不能修改长度
  4. 空元组tuple_name=()
  5. #如果创建的元组只有一个元素,那么该元素后面的逗号是不可忽略的(1,)
  6. #不可修改元素

>>>user=(1,2,3)

>>>user[0]=2

Traceback(mostrecentcalllast):

File"<pyshell#5>",line1,in<module>

user[0]=2

TypeError:'tuple'objectdoesnotsupportitemassignment

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


**习题**

**#求序列类型的最大元素和最小元素**

**#入口:序列类型List**

**#返回: (最大元素,最小元素) 应用元组**

**sample**

def hello(): return 'hello','world' print hello()

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。