标签:*** err ack 双层 报错 exe call rac 索引
下面给大家介绍以下元组的相关知识:
·元组可以看成是一个不可更改的list
1.元组的创建
# 创建空元祖 t = () print(type(t)) # 创建只有一个值的元组 # 观察可知元组中如果纯数字的话,类型是int,加个逗号就好了 t1 = (1) t2 = (1,) print(type(t1)) print(type(t2)) t = 1,# 也要有逗号 print(type(t)) print(t) # 创建多个值的元组类型1 t = (1,2,3,4,5) print(type(t)) print(t) # 创建多个值的元组类型2 t = 1,2,3,4,5 print(type(t)) print(t) # 使用其他结构创建 l = [1,2,3,4,5] t = tuple(l) print(type(t)) print(t)
<class ‘tuple‘>
<class ‘int‘>
<class ‘tuple‘>
<class ‘tuple‘>
(1,)
<class ‘tuple‘>
(1, 2, 3, 4, 5)
<class ‘tuple‘>
(1, 2, 3, 4, 5)
<class ‘tuple‘>
(1, 2, 3, 4, 5)
元组的特性
# 索引操作 t = (1,2,3,45) print(t[2])
3
# 超标在list中超标是会报错的,而tuple中不会报错 #list中 print(t[12])
报错:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-97-81e870641898> in <module>()
1 # 超标在list中超标是会报错的,而tuple中不会报错
----> 2 print(t[12])
IndexError: tuple index out of range
t = (1,2,3,4,5,6) t1 = t[1::2] print(id(t)) print(id(t1)) print(t1) # tuple中的切片是不报错的 print(t[1:200])
140106142035688 140106141748032 (2, 4, 6) (2, 3, 4, 5, 6)
# 序列相加 t1 = (1,2,3) t2 = (4,5,6) # 传址操作 print(t1) print(id(t1)) t1 = t1 + t2 print(t1) print(id(t1)) # 以上操作,类似于 t1 = (1,2,3) t1 = (2,3,4) # tuple 的不可修改,指的是内容的不可修改 # 修改tuple内容会导致报错 t1[1] = 100
(1, 2, 3) 140106142173296 (1, 2, 3, 4, 5, 6) 140106142035688
# 元组相乘 t = (1,2,3) t = t*3 print(t)
(1, 2, 3, 1, 2, 3, 1, 2, 3)
# 成员检测 t = (1,2,3) if 2 in t: print("yes") else: print("no")
yes
# 元组遍历,一般采用for循环 # 1.单层元组遍历 t = (1,2,3,"python","java") for i in t: print(i,end=" ")
1 2 3 python java
# 2.双层元组遍历 t = ((1,2,3),("python","java","c")) #比对以上元组的遍历,可以如下 #1. for i in t: print(i,end=" ") print() for k,m,n in t: print(k,"--",m,"--",n)
(1, 2, 3) (‘python‘, ‘java‘, ‘c‘) 1 -- 2 -- 3 python -- java -- c
关于元组的函数:
# len:获取元组的长度 t = (1,2,3,4,5) len(t) print(len(t))
# tuple:转换或创建元组 l = [1,2,3,14,5,60] t = tuple(l) print(t) t = tuple() print(t)
(1, 2, 3, 14, 5, 60) ()
# count: 计算指定数据出现的次数 t = (1,2,1,2,6,5,1) print(t.count(1))
3
# index :求制定元素在元组中的索引位置 print(t.index(6)) #如果需要查找的数字是多个,则返回第一个 print(t.index(1))
4
0
元组变量交换法
# 俩个变量交换值 a = 1 b = 3 print(a) print(b) print("*"*30) # Java程序员会这么写 c = a a = b b = c print(a) print(b) print("*"*30) # python程序员的写法 a,b=b,a print(a) print(b)
1 3 ****************************** 3 1 ****************************** 1 3
标签:*** err ack 双层 报错 exe call rac 索引
原文地址:https://www.cnblogs.com/cswzp/p/10000286.html