元祖创建
元祖创建简单,只需在括号中添加元素,元素间用逗号隔开,元祖元素不可修改,例子:
>>> tuple1 = ("hello","world",1970,1999)
>>> tuple1
('hello', 'world', 1970, 1999)
创建空元祖,例子:
>>> tuple1 = ()
>>> tuple1
()
元祖中只包含一个元素时,需在元素后面添加逗号,例子:
>>> tuple1 = (50,)
>>> tuple1
(50,)
元祖访问
元祖使用下标索引访问元祖中元素,例子:
例一:
>>> tuple1 = ("hello","world",1970,1999)
>>> tuple1[1]
'world'
例二:
>>> tuple1 = ("hello","world",1970,1999)
>>> tuple1[1:3]
('world', 1970)
元祖修改
元祖中的元素不允许修改,可以通过元祖进行连接组合,例子:
例一:
>>> tuple1 = (1,2,3,4,5)
>>> tuple2 = (7,8,9)
>>> tuple3 = tuple1 + tuple2
>>> tuple3
(1, 2, 3, 4, 5, 7, 8, 9)
例二:
>>> tuple1 = (1,2,3,4,5)
>>> tuple2 = (7,8,9)
>>> tuple1 = tuple1[2:4] + tuple2[0:2]
>>> tuple1
(3, 4, 7, 8)
元祖删除
元祖中的元素是不允许删除的,可以通过del删除整个元祖,例子:
>>> tuple1 = (1,2,3,4,5)
>>> del tuple1
>>> tuple1
元祖无关闭分隔符
以逗号分开无关闭的分隔开符的对象,默认为元祖,例子:
def return_tuple(x,y):
return x,y
if __name__ == "__main__":
x = 1
y = 2
return_tuple_value = return_tuple(x,y)
print "return_tuple_value:" + str(return_tuple_value)
print "return_tuple_value type:" + str(type(return_tuple_value))
return_tuple_value:(1, 2)
return_tuple_value type:<type 'tuple'>
元祖运算符:+、*、[]、[:] 、in、for i in tuple_demo
操作符 | 描述 | 实例 |
+ | 组合 | >>> tuple1 = (1,2,3,4,5) >>> tuple2 = (7,8,9) >>> tuple3 = tuple1 + tuple2 >>> tuple3 (1, 2, 3, 4, 5, 7, 8, 9) |
* | 重复 | >>> tuple1 = ("hello","world") |
[] | 索引 | >>> tuple1 = ("hello","world",1970,1999) >>> tuple1[1] |
[:] | 截取 | >>> tuple1 = ("hello","world",1970,1999) >>> tuple1[1:3] ('world', 1970) |
in | 成员运算符--元素存在元祖中返回True | >>> tuple1 = (1,2,3,4,5,6) |
not in | 成员运算符--元素不存在元祖中返回True | >>> tuple1 = (1,2,3,4,5,6) |
for in tuple_demo | 迭代 | >>> tuple1 = (1,2,3,4,5,6) 1 |
元祖函数
语法 | 描述 | 参数 | 返回 | 实例 |
cmp(tuple1,tuple2) | 比较两个元祖元素 | tuple1--比较元祖 tuple2-比较元祖 | tuple1 < tuple2:-1 tuple1 > tuple2:1 tuple1 == tuple2:0 | >>> tuple1 = (1,2,3) |
len(tuple) | 计算元祖中元素个数 | tuple--需要计算长度的元祖 | 元祖中元素个数 | >>> tuple1 = (1,2,3,4) |
max(tuple) | 返回元祖中最大的元素 | tuple--需要返回最大值元素的元祖 | 元祖中最大值的元素 | >>> tuple1 = (1,2,3,4) |
min(tuple) | 返回元祖中最小的元素 | tuple--需要返回最小值元素的元祖 | 元祖中最小值的元素 | >>> tuple1 = (1,2,3,4) |
tuple(seq) | 将有序String和list转换成tuple | seq--需要转换成tuple的string或list | 返回转换后的元祖 | >>> str1 = "hello python!!!" >>> list1 = [1,2,3,4,5,6] |