- 对比Excel,轻松学习Python数据分析(入职数据分析师系列)
- 张俊红
- 342字
- 2025-02-17 15:00:11
2.8 数据结构——元组
2.8.1 元组的概念
元组(tup)虽然与列表类似,但也有不同之处,元组的元素不能修改;元组使用小括号,而列表使用中括号。
2.8.2 新建一个元组
元组的创建比较简单,直接将一组数据元素用小括号括起来即可。

2.8.3 获取元组的长度
获取元组长度的方法与获取列表长度的方法是一样的,都使用函数len()。

2.8.4 获取元组内的元素
元组内元素的获取方法主要分为普通索引和切片索引两种。
普通索引

切片索引

2.8.5 元组与列表相互转换
元组和列表是两种相似的数据结构,两者经常互相转换。
使用函数list()将元组转化为列表。

使用函数tuple()将列表转化为元组。

2.8.6 zip()函数
zip()函数用于将可迭代的对象(列表、元组)作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。zip()函数常与 for 循环一起搭配使用。
当可迭代对象是列表时:


当可迭代对象是元组时:
