为何要有元组 ,() 可存放多个值 元组不可变 更多的是用来查询t = (1,[1,3],‘sss‘,(1,2)) #t = tuple(1,[1,3],‘sss‘,(1,2))print (type(t)) 元组可以作为字典的keyd={(1,2,3):‘zcx‘}print(d,type(d),d[(1,2,3)]) 索引取值d = (1,2,3,4,5)print(d[1]) 切片goods = (‘iphone‘,‘lenove‘,‘sum‘,‘vivo‘)print(goods[1:3])print((goods)) 长度goods = (‘iphone‘,‘lenove‘,‘sum‘,‘vivo‘)print(len(goods)) 包含goods = (‘iphone‘,‘lenove‘,‘sum‘,‘vivo‘)print(‘iphone‘ in goods) 掌握index、countgoods = (‘iphone‘,‘lenove‘,‘sum‘,‘vivo‘)print(goods.index(‘lenove‘)) #查询索引位置print(goods.count(‘lenove‘)) #计数 补充:元组本身是不可变的,但是 内部子元素可改变。t=(1,[‘a‘,‘b‘],‘sss‘,(1,2))t = ([1],[0],‘A‘)print (type(t)) 不依赖索引的取值msg_dic={ ‘asd‘:1111, ‘qwe‘:1222, ‘zxc‘:33333}for item in msg_dic: print (item,msg_dic) msg= ‘hello‘# msg = [1,2,3]msg = (1,2,3)for item in msg: print(item) for:补充len () 取索引 print 之后在取值range: 顾头不顾尾 默认从0开始for i in range (1,10,2): print (i)for i in range (10,1,-1): print (i)
时间: 2024-11-08 12:39:04