Python 元组,,与列表相似,元组Tu
Python 元组,,与列表相似,元组Tu
与列表相似,元组Tuple也是个有序序列,但是元组是不可变的,用()生成。
t = (10, 11, 12, 13, 14)print(t)#(10, 11, 12, 13, 14)可以索引,切片:print(t[0])#10prinnt(t[1:3])#(11, 12)
但是元组是不可变的:
# 会报错t[0] = 1"""---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-4-da6c1cabf0b0> in <module>() 1 # 会报错----> 2 t[0] = 1TypeError: ‘tuple‘ object does not support item assignment"""
单个元素的元组生成
由于()在表达式中被应用,只含有单个元素的元组容易和表达式混淆,所以采用下列方式定义只有一个元素的元组:
a = (10,)print aprint type(a)#(10,)#<type ‘tuple‘>a = (10)print type(a)#<type ‘int‘>
将列表转换为元组:
a = [10, 11, 12, 13, 14] tuple(a) #(10, 11, 12, 13, 14)
元组方法
由于元组是不可变的,所以只能有一些不可变的方法,例如计算元素个数 count 和元素位置 index ,用法与列表一样。
a.count(10)#1a.index(12)#2
删除元组
元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组,如下实例:
#!/usr/bin/python3tup = (‘Google‘, ‘Runoob‘, 1997, 2000)print (tup)del tup;print ("删除后的元组 tup : ")print (tup)
以上实例元组被删除后,输出变量会有异常信息,输出如下所示:
删除后的元组 tup :
Traceback (most recent call last):
File "test.py", line 8, in <module>
print (tup)
NameError: name ‘tup‘ is not defined
元组内置函数
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‘)
为什么需要元组
旧式字符串格式化中参数要用元组;
在字典中当作键值;
数据库的返回值……
Python 元组
相关内容
- pycharm 安装及使用,,pycharm 的使
- python中列表(list)函数及使用,,序列是Python中
- Python的字典 { },,Python的字典属
- Python3.7之抽象类与归一化,,Python3.7之
- python dic字典使用,,‘‘‘字典的基本组成
- Python中str()与repr()函数的区别——repr() 的输出追求明确
- python排序(冒泡、直接选择、直接插入等),,冒泡排序冒
- from __future__ import print_function的作用,,阅读代码的时候
- Python IF 条件判断,,if 语句用于控制程
- python3实现TCP协议的简单服务器和客户端,,利用python3来
评论关闭