您的位置:首页 > 理论基础 > 数据结构算法

Python常用数据结构--元组

2018-03-24 22:30 183 查看
元组介绍

Python的元组与列表类似,不同之处在于元组的元素不能修改。元组使用小括号,列表使用方括号。

一、元组的创建
>>> aTuple = ('et',77,99.9)
>>> aTuple
('et',77,99.9)

>>>t = (1,)
        >>>t

        (1,)

>>> t = ()
        >>>t

        ()

 从上面我们可以分析得出:
    a、逗号分隔一些值,元组自动创建完成;
    b、元组大部分时候是通过圆括号括起来的;
    c、空元组可以用没有包含内容的圆括号来表示;

    d、只含一个值的元组,必须加个逗号(,);

tuple函数和序列的list函数几乎一样:以一个序列(注意是序列)作为参数并把它转换为元组。如果参数就算元组,那么该参数就会原样返回:

t1=tuple([1,2,3])
t2=tuple("jeff")
t3=tuple((1,2,3))
print t1
print t2
print t3
t4=tuple(123)
print t45
输出:

(1, 2, 3)
('j', 'e', 'f', 'f')
(1, 2, 3)

Traceback (most recent call last):
  File "F:\Python\test.py", line 7, in <module>
    t4=tuple(123)
TypeError: 'int' object is not iterable

二、元组的常见操作
1、访问元组
>>>tuple = ('hello',100,3.14)
>>>tuple[0]
>>>hello
>>>tuple[1]
>>>100
>>>tuple[2]
>>>3.14

2、修改元组
元组中的元素值是不允许修改的(包括不可以删除元素),但我们可以对元组进行连接组合
>>>tuple[2] = 188
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>>
说明:Python中不支持修改元组的数据,包括不能删除其中的元素。

>>>tup1 = (12,34,56)
>>>tup2 = ('abc','xyz')
>>>tup3 = tup1 + tup2
>>>print(tup3)
>>>(12,34,56,'abc','xyz')

3、元组的遍历
>>>tup = (1,2,3,4)
>>>for num in tup:
>>>    print(num,end="")
>>>1 2 3 4 5

4、元组的内置函数
count和index与字符串和列表中的用法相同
>>> a = ('a', 'b', 'c', 'a', 'b')
>>> a.index('a', 1, 3) #注意是左闭右开区间
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: tuple.index(x): x not in tuple
>>> a.index('a', 1, 4)
3
>>> a.count('b')
2
>>> a.count('d')
0

   方法                描述
len(tuple)       计算元组元素个数
max(tuple)       返回元组中元素最大值
min(tuple)       返回元组中元素最小值
tuple(seq)       将列表转换为元组
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: