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
举例:
tuple1=(1,2,3,4,5,6,7,8,9) print(len(tuple1))
输出:
9
举例:
tuple1=(1,2,3,4,5,6,7,8,9) print(max(tuple1)) print(min(tuple1))
输出:
9
1
举例:
tuple1=(1,2,3,4,5,6,7,8,9,3,3,2,2) print(tuple1.count(3))
输出:
3
举例:
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)
输出:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
长按识别二维码并关注微信
更方便到期提醒、手机管理