栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

元组(tuple) - Python对象

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

元组(tuple) - Python对象

在上节我们学习了python中列表的基础使用,我们本节来对元组进行基础的学习。

列表中的元素是可变的(即可进行增删改),我们将其称为可变序列。

而我们今天要学习的数组,其本身不可增删元素,也不能进行元素的修改,所以元组又称为不可变的列表。

1.元组的创建

变量名 = (元素, ...)

变量名 = tuple((元素, ...))

如:

a = (10, 20, "hello")
print(a)
print(type(a))

输出结果为:

(10, 20, 'hello')

对于创建a时的(10, 20, "hello")中,括号可以省略,即:

a2 = 10, 20, "hello"
print(a2)
print(type(a2))

(10, 20, 'hello')

b = tuple((10, 50, "hello"))
print(b)
print(type(b))

(10, 50, 'cnm')

但注意,下列的创建方式是错误的:

b = tuple(110, 50, 11)

即在使用tuple创建元组时,括号是不可省略的。

另外,创建单个元素的元组时,必须在元素后加上逗号“,”,否则该变量直接指向该元素(即把括号省略了),如:

d1 = ("hello")
d2 = ("hello",)
print(d1)
print(type(d1))
print(d2)
print(type(d2))

输出结果为:

hello

('hello',)

2.元组的遍历

元组的遍历与列表遍历相似:

for 迭代变量 in 元组:

        代码块

如:

f = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
for i in f:
    print(i, end=" ")

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 

3.元组的注意事项

元组是不可变序列,其值不能发生变化(确切的说其实是其元素的id(类似于指针)不能发生改变)。如有下面一个元组,如果我们试图改变其内的元素:

e = (10, 20, 50)
print(e)
e[2] = 30

结果为:

(10, 20, 50)
Traceback (most recent call last):
  File "test.py", line 3, in
    e[2] = 30
TypeError: 'tuple' object does not support item assignment

但,如果其内部的元素是如列表这类进行操作id不会发生改变的,又可以进行更改:

e = (10, [20, 30], 50)
print(e)
e[1].append(40)
print(e)

输出结果为:

(10, [20, 30], 50)
(10, [20, 30, 40], 50)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/859013.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号