零基础学Python:list(列表)和tuple(元组)
数据容器
Python 最的基本数据类型:布尔型、整型、浮点型以及字符串型。
本章将要提到的 数据结构(容器) 。在这一章中,我们会把之前所学的基本 Python 类型以更为复杂的方式组织起来。这些数据结构以后会经常用到。在编程中,最常见的工作就是将数据进行拆分或合并,将其加工为特定的形式
大多数编程语言都有特定的数据结构来存储由一系列元素组成的序列,这些元素以它们所处的位置为索引:从第一个到最后一个依次编号。
1.list(列表)
定义:列表是一种可变的、有序的数据结构,可以随时添加和删除其中的元素。
列表非常适合利用顺序和位置定位某一元素,尤其是当元素的顺序或内容经常发生改变时。与字符串不同,列表是可变的。你可以直接对原始列表进行修改:添加新元素、删除或覆盖已有元素。
创建列表
![](https://upload-images.jianshu.io/upload_images/25631092-4542e1b73b3f7295.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![](https://upload-images.jianshu.io/upload_images/25631092-6ee2869f62bb1c1f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
注意:从列表中取值时,如果 超出索引范围,程序会报错
![](https://upload-images.jianshu.io/upload_images/25631092-bedbf99d95ab9095.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
创建一个列表
![](https://upload-images.jianshu.io/upload_images/25631092-147943bc6cd4f5ee.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
类型转化
将其他 序列 类型转化为列表
![](https://upload-images.jianshu.io/upload_images/25631092-b83b2f5f9ffe546d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
列表取值
使用[offset]获取与修改元素
![](https://upload-images.jianshu.io/upload_images/25631092-c2c454e15d03c7e6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
根据索引位置修改内容
![](https://upload-images.jianshu.io/upload_images/25631092-b86ffd7f048ae520.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
列表切片
切片使用索引值来限定范围,从一个大的数据容器中切出小的字符串
Python中符合序列的有序序列都支持切片(slice),例如列表,字符串,元组。
切片 方法适用于 字符串、列表、元组
![](https://upload-images.jianshu.io/upload_images/25631092-0371507b658a1d72.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![](https://upload-images.jianshu.io/upload_images/25631092-76bd66f64909bb2a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![](https://upload-images.jianshu.io/upload_images/25631092-f4adaa703cb1a586.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
2.tuple(元组)
创建元组
![](https://upload-images.jianshu.io/upload_images/25631092-95b1583ee643f1b0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![](https://upload-images.jianshu.io/upload_images/25631092-e6d5683aa1965a00.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
元组中只包含一个元素时,需要在元素后面添加逗号
![](https://upload-images.jianshu.io/upload_images/25631092-b575037e920dae82.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
元组取值与切片
![](https://upload-images.jianshu.io/upload_images/25631092-a1c594fa0e0baf78.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![](https://upload-images.jianshu.io/upload_images/25631092-7398ba1f116f8424.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![](https://upload-images.jianshu.io/upload_images/25631092-42856bbdf6451dd0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
用逗号创建只有一个元素的元组:(1,)
![](https://upload-images.jianshu.io/upload_images/25631092-c6b932e6b41692a5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)