python系列-元组

1.元组的定义

name_tuple = (元素1, 元素2,....元素n)

如果元组是空的,定义如下:

name_tuple = ()

如果元素有一个元素,则如下定义:

name_tuple = (元素,) # 元素后面有一个逗号

注意:列表的数据可以更新,而元组的元素值与元素个数不可更改。

2.读取元组元素

读取元组元素和列表一样,都是通过[索引]来读取,索引值从0开始

例如:

tuple_1 = ('apple', 'orange', 'strawberry')

print(tuple_1[0])

输出:

apple

3.更改元组元素

一般情况下,元组的元素是不可更改的,此处我们尝试更改一下元组的元素值,看看会出现什么情况:

tuple_1[1] = 'egg'

print(tuple_1[1])

不出所料,报错了

tuple_1[1] = 'egg'

TypeError: 'tuple' object does not support item assignment 

证实了元组的元素值是不可更改的。

如果我们真想更改元组元素,可有方法,答案是肯定的。更改方法-------重新定义元组 或者 元组进行连接组合

举例说明 重新定义元组

tuple_2 = (1, 2, 3, 4)

print('更改前元组:',tuple_2)

#重新定义tuple_2元组

tuple_2 = (1, 22, 3, 44)

print('更改后的元组:', tuple_2)

程序输出:

更改前元组: (1, 2, 3, 4)

更改后的元组: (1, 22, 3, 44)

实例 元组连接更改元组

tuple_3 = ('hello', 'world')

tuple_4 = ('python', 'tuple')

print(tuple_3)

print(tuple_4)

tuple_3 = tuple_3 +tuple_4

print('连接后元组:',tuple_3)

程序输出:

('hello', 'world')

('python', 'tuple')

连接后元组: ('hello', 'world', 'python', 'tuple')

4.删除元组

元组中的元素值不能删除,可以使用del语句删除整个元组,或者对元组重新定义一个空元组

tuple_5 = ('zhangsan',  'lisi')

print('del删除前', tuple_5)

del tuple_5

print('del tuple', tuple_5)

程序输出:

del删除前 ('zhangsan', 'lisi')

Traceback (most recent call last):

  File "D:/pyProject/study/hgp_list.py", line 66, in <module>

    print('del tuple', tuple_5)

NameError: name 'tuple_5' is not defined

上面报错是删除元组后,元组不存在了,再次访问了tuple_5,告诉我们tuple_5没有定义

5.元组与列表相互转换

  将列表转换为元组使用函数:tuple()

将元组转换为列表使用函数:list()

具体使用方法我们看一下

tuple_6 = ('zhangsan', '18', 'beijing')

list_1 = [11, 33, 22, 66]

print('元组转换前打印', tuple_6)

print('元组转换后打印', list(tuple_6))

print('列表转换前打印', list_1)

print('列表转换后打印', tuple(tuple_6))

程序输出:

元组转换前打印 ('zhangsan', '18', 'beijing')

元组转换后打印 ['zhangsan', '18', 'beijing']

列表转换前打印 [11, 33, 22, 66]

列表转换后打印 ('zhangsan', '18', 'beijing')

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容