python 元组tuple
# -*- coding: utf8 -*-
"""
元组的相关测试, 基本和列表一模一样,除了元素不能被修改,元组用小括号括起,实际起作用的是逗号
"""
#定义
#空元组
tuple1 = ()
#创建一个元素,和列表有所区别
tupleOne1 = ('hello',)
tupleOne2 = 'hello', #小括号可以不加,但最好加上
tupleOne3 = tuple(('hello',))
print(tupleOne1) #('hello',)
print(tupleOne2) #('hello',)
print(tupleOne3) #('hello',)
#创建方式
tuple2 = ('a', 2.2, (1, 'b'), {'pi': 3.14}, 3e-2)
print(tuple2) #('a', 2.2, (1, 'b'), {'pi': 3.14}, 0.03)
strTemp = 'hello'
tuple3 = tuple(strTemp)
print(tuple3) #('h', 'e', 'l', 'l', 'o')
tuple333 = tuple(('hello',)) #注意传入的是一个元组,此处可简写成tuple333 = ('hello',)
print(tuple333) #('h', 'e', 'l', 'l', 'o')
strTemp = 'worlld'
print(tuple3)
list1 = [1, 'a', 3.3]
tuple4 = tuple(list1)
print(tuple4) #(1, 'a', 3.3)
#修改元组元素,只能通过拼接的方法'修改'
#tuple4[1] = 'b' #肯定报错:TypeError: 'tuple' object does not support item assignment(元组不支持里面的项被改变)
tuple4 = tuple4[:1] + ('new',) + tuple4[1:] #注意要加逗号(1, 'new', 'a', 3.3)
print(tuple4) #(1, 'a', 3.3)
#直接赋值不会创建新内存,只是等于这块内存多了一个标签
tuple5 = tuple2
print('t5=%d, t2=%d' % (id(tuple5), id(tuple2)))
print(tuple5) #('a', 2.2, (1, 'b'), {'pi': 3.14}, 0.03)
tuple2 = tuple2[:1] + tuple2[2]
print(tuple2) #('a', 1, 'b')
print(tuple5) #('a', 2.2, (1, 'b'), {'pi': 3.14}, 0.03)
#长度
tuple6 = (1, 3, 4)
print(len(tuple6)) #3
#查找某一个元素的个数
print(tuple6.count(3)) #1 个数1个
#查找该元素第一次出现的位置索引
print(tuple6.index(4)) #2 ,索引为2
print(tuple6.index(4,0,3)) #2 ,索引为2, 索引区间[0, 3),不包含3
print(tuple6.index(4,1)) #2 ,索引为2, 索引区间[1, 3),不包含3
#print(tuple6.index(4, 0, 2)) #报异常,搜不到这个值在该区间内 ValueError: tuple.index(x): x not in tuple
#元组的比较
print(max(tuple6)) #4
tuple66 = ('a', 2.2, (1, 'b'), {'pi': 3.14}, 0.03)
print(max(tuple66)) #(1, 'b') 暂时不知道为什么
tuple7 = ('a','b','c')
tuple8 = ('e', 'f', 'g')
print(min(tuple7)) #a
print(cmp(tuple7, tuple8)) #-1, 即tuple7<tuple8 (注:0相等,1大于)
#删除元素,只能通过拼接的方法'删除'
tuple6 = (1, 2, 3, 4)
#del(tuple6[1]) #肯定报错,不能修改内部元素,TypeError: 'tuple' object doesn't support item deletion
tuple6 = tuple6[:1] + tuple6[2:]
print(tuple6) #(1, 3, 4)
#清空
del(tuple6)
tuple7 = [1, 2, 3.4, 4, 5, 6]
print(max(tuple7)) #6
print(min(tuple7)) #1
print(tuple7[2]) #3.4
print(tuple7[-2]) #5 加个负号就相当于从后往前查找 tuple7[-n] == tuple7[len(li) - n]
print(tuple7[-0]) #1 相当于list12[0],
相关文章