Python元组
从未止步.. 人气:0元组的创建
tuple=() #创建一个空元组 print(tuple) print(type(tuple))
输出:
()
<class 'tuple'>
定义只包含一个元素的元组:元素后面必须加逗号,否则编译器会将它识别成整形。
举例:
tuple2 = (1,) print(tuple2) print(type(tuple2)) tuple2 = (1) print(tuple2) print(type(tuple2))
输出:
(1,)
<class 'tuple'>
1
<class 'int'>
元组的删除
del 需要删除的元组名
tuple2 = (1,2,3,4,5,6) print(tuple2) del tuple2 print(tuple2)
由于我们在第三行代码对tuple2进行了删除,所以编译器会进行报错,tuple2没有被定义。
判断某个元素是否在元组中:in/ not in 语句
举例:
tuple2 = (1,2,3,4,5,6) if 4 in tuple2: print("YES") else: print("NO") if 10 in tuple2: print("YES") else: print("NO")
输出:
YES
NO
元组部分元素的输出
与列表的切片相似。
举例:
tuple2 = (1,2,3,4,5,6) print(tuple2[0:3])
输出:
(1, 2, 3)
元组的嵌套
和列表的嵌套相类似,只不过将列表换成了元组
举例:
tuple1=((1,2,3),(4,5,6),(7,8,9)) for tuple1s in tuple1: print(tuple1s) for tuple1_s in tuple1s: print(tuple1_s)
输出:
(1, 2, 3)
1
2
3
(4, 5, 6)
4
5
6
(7, 8, 9)
7
8
9
元组元素的个数计算:len()
举例:
tuple1=(1,2,3,4,5,6,7,8,9) print(len(tuple1))
输出:
9
元组中的元素最大最小值的求解:max(),min()
举例:
tuple1=(1,2,3,4,5,6,7,8,9) print(max(tuple1)) print(min(tuple1))
输出:
9
1
元组中某元素出现的次数:count函数
举例:
tuple1=(1,2,3,4,5,6,7,8,9,3,3,2,2) print(tuple1.count(3))
输出:
3
元组中某元素的索引:index(),返回的为下标值
举例:
tuple1=(1,2,3,4,5,6,7,8,9,3,3,2,2) print(tuple1.index(2))
输出:
1
元组元素值的修改:元组的元素值不能进行修改。
举例:
tuple1=(1,2,3,4,5,6,7,8,9,3,3,2,2) tuple1[3]=100 print(tuple1)
输出:
加载全部内容