Python3 元组
元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当作运算符使用:
>>> tup1 = (50) >>> type(tup1) # 不加逗号,类型为整型 <class 'int'> >>> tup1 = (50,) >>> type(tup1) # 加上逗号,类型为元组 <class 'tuple'>
# 访问元组中的值(用下标索引) tup = (2, 3, 5, 9) print(tup[2]) print(tup[2:4])
输出结果:
5
(5,9)
元组中的元素值不允许修改也不允许删除,但是与字符串一算,可以访问元组中的指定位置的元素,也可以截取索引中的一段元素。
元组内置函数
Python元组包含了以下内置函数
序号 | 方法及描述 | 实例 |
---|---|---|
1 | len(tuple) 计算元组元素个数。 |
>>> tuple1 = ('Google', 'Runoob', 'Taobao') >>> len(tuple1) 3 >>> |
2 | max(tuple) 返回元组中元素最大值。 |
>>> tuple2 = ('5', '4', '8') >>> max(tuple2) '8' >>> |
3 | min(tuple) 返回元组中元素最小值。 |
>>> tuple2 = ('5', '4', '8') >>> min(tuple2) '4' >>> |
4 | tuple(seq) 将列表转换为元组。 |
>>> list1= ['Google', 'Taobao', 'Runoob', 'Baidu'] >>> tuple1=tuple(list1) >>> tuple1 ('Google', 'Taobao', 'Runoob', 'Baidu') |