Python3元组

来源:互联网 发布:淘宝促销短信模板 编辑:程序博客网 时间:2024/05/18 23:56

元组与列表类似,但是元素不能修改。元组使用小括号,列表使用中括号。

元组例子:

>>> tupe1=('a',1)>>> type(tupe1)<class 'tuple'>>>> tupe3="a",1>>> print(tupe3)('a', 1)>>> tupe2=()

访问元组

>>> tupe1=('a','b')>>> print(tupe1[1])b>>> print(tupe1[0:])('a', 'b')

修改元素

不可以修改元组元素

删除元组

>>> tupe1=('a','b') >>> del tupe1>>> tupe1Traceback (most recent call last):  File "<stdin>", line 1, in <module>NameError: name 'tupe1' is not defined

元组运算符

跟字符串一样,可以进行+和*运算,组合和复制

>>> tupe1=('a','b',3)>>> len(tupe1)3>>> tupe1+tupe1('a', 'b', 3, 'a', 'b', 3)>>> tupe1*3('a', 'b', 3, 'a', 'b', 3, 'a', 'b', 3)>>> 'a' in tupe1True>>> for x in tupe1:...     print(x)... ab3

元组索引,截取

>>> tupe1=('a','b',3)>>> tupe1[1]'b'>>> tupe1[-1]3>>> tupe1[1:]('b', 3)

元组内置函数

len(tupe1) 计算元组元素个数

max(tupe1) 返回元组中最大元素

min(tupe1) 返回元组中最小元素

tupe(list1) 转换列表为元组

>>> tupe1=('a','b',3)>>> max(tupe1)Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: '>' not supported between instances of 'int' and 'str'>>> tupe2=(1,2,3)    >>> max(tupe2)   3>>> list1=['a','b']>>> type(list1)<class 'list'>>>> tupe3=tuple(list1)>>> type(tupe3)<class 'tuple'>

元组和序列

元组由若干逗号分隔

>>> list0=1,2,3>>> type(list0)<class 'tuple'>>>> list1=[1,2,3]>>> type(list1)<class 'list'>


0 0