Python 元组

与列表相似,元组Tuple也是个有序序列,但是元组是不可变的,用()生成。

t = (10, 11, 12, 13, 14)
print(t)
#(10, 11, 12, 13, 14)
可以索引,切片:
print(t[0])
#10
prinnt(t[1:3])
#(11, 12)


但是元组是不可变的:

# 会报错
t[0] = 1
"""
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-da6c1cabf0b0> in <module>()
      1 # 会报错
----> 2 t[0] = 1

TypeError: 'tuple' object does not support item assignment
"""

...

#coding=utf-8
tup1=(1,2,3)
tup2=(4,5,6)
print(tup1+tup2)


单个元素的元组生成
由于()在表达式中被应用,只含有单个元素的元组容易和表达式混淆,所以采用下列方式定义只有一个元素的元组:

a = (10,)
print a
print 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)
#1
a.index(12)
#2


删除元组
    元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组,如下实例:

#!/usr/bin/python3

tup = ('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

元组的索引和切片

#coding=utf-8
tup=(1,2,3,4)
print(tup[0])
print(tup[-1])
print(tup[6])
 
print(tup[1:])
print(tup[1:3])
print(tup[:-2])
print(tup[1:-1])



元组内置函数
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')

为什么需要元组
    旧式字符串格式化中参数要用元组;
    在字典中当作键值;
    数据库的返回值……

原文地址:https://www.cnblogs.com/mysterious-killer/p/10040024.html