python元组tuple,及常用函数

前面的章节我们较为详细地介绍了python的列表,python的元组tuple与列表有许多相似的地方,比如支持索引,支持切片,也支持迭代。这一节我们将着重介绍一下元组与列表不同的一些地方,相同的地方我们会用例子简单介绍一下。

python元组tuple的声明

元组的数据结构为(var1, var2, var3),用括号,而不是列表那样的中括号,除此之外,列表只有一个元素时不用再末尾添加“,”,而元组需要。

tuple声明示例

>>> a = (1,2,3) #声明一个元组变量
>>> type(a)
<class 'tuple'>
>>> b = (1,) #声明一个只有一个元素的元组变量,末尾必须添加逗号
>>> type(b)
<class 'tuple'> 
>>> c = (1) #如果不加逗号
>>> type(c)
<class 'int'>  #数据类型变成int整型
>>> d = ('x1y1z1.com') #仍然没有加逗号
>>> type(d)
<class 'str'> 
>>> e = tuple(range(1,10)) #和列表的list()函数一样,可以用tuple()函数将range类型的数据转换成元组
>>> e
(1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> type(e)
<class 'tuple'>  

python的元组支持索引和切片,但不可修改

正是因为如此,很多程序设计人员为了保证数据的安全性(避免在程序运行过程中被修改)会常常用元组代替列表。不过不怎么常用,像大数据和机器学习当中就是为了能够处理数据,所以还是用列表居多。

示例

>>> a = tuple(range(1,10))
>>> a
(1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> a[0]
1
>>> a[-1]
9
>>> a[:]
(1, 2, 3, 4, 5, 6, 7, 8, 9) 
>>> a[1:8]
(2, 3, 4, 5, 6, 7, 8)
>>> a[:8:2] #支持切片的step
(1, 3, 5, 7)

>>> a[0] = 10 #元组不支持元素的修改,否则将发生错误
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment


>>> a.replace(1,10) #元组也不支持用replace()函数修改元素
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'replace'


>>> a.pop() #元素也不支持用pop()函数删除元素
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'pop' 


>>> a.append(10) #元素也不支持用append()函数添加元素
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append' 

总之,试图修改元组内部元素的程序都可能发生错误。

元组的基本运算

元组的基本运算与列表的基本相似。

示例

>>> (1,2,3)+(6,7,8)
(1, 2, 3, 6, 7, 8)
>>> (1,2)*3
(1, 2, 1, 2, 1, 2)

元组的一些常用函数

列表list的常用函数count()、index()、len()、max()、min()等也同样适用于元组tuple。

示例

>>> a = tuple(range(1,10))
>>> a
(1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> len(a)
9
>>> a.count(1)
1
>>> a.index(9)
8
>>> max(a)
9
>>> min(a)
1

元组的迭代和for循环

元组也是python当中支持迭代的数据类型。

元组迭代示例

我们将写一个与max()一样求元组中元素最大值的函数,大家可以打开jupyter notebook。

In[1] : a = tuple(range(1,10))
def max_self(tup):
    Max_Number = -float('inf') #先声明一个负无穷大
    for i in tup: #遍历元组tup
        if Max_Number < i:
            Max_Number = i #如果元素i大于Max_Number,就将i赋值给Max_Number
    return Max_Number
mn = max_self(a)
print(mn)
9

python的元组数据类型就介绍到这里,下一章节我们将继续介绍python的另一种数据类型——字典dict


全栈后端 / python教程 :


























Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.