Python使用list一、listPython内置的一种数据类型是列表:list。list是一种有序的集合,可以随时添加和删除其中的元素。 比如,列出班里所有同学的名字,就可以用一个list表示: classmates = ['Michael', 'Bob', 'Tracy'] print(classmates)
![](http://image109.360doc.com/DownloadImg/2023/02/1011/260410675_1_20230210111313239.png)
变量classmates就是一个list。
len()函数1. 获得list元素的个数:classmates = ['Michael', 'Bob', 'Tracy'] print(len(classmates))
![](http://image109.360doc.com/DownloadImg/2023/02/1011/260410675_2_20230210111313411.png)
用索引来访问list中每一个位置的元素,记得索引是从0 开始的:
classmates = ['Michael', 'Bob', 'Tracy']
print(classmates[0])
print(classmates[1])
print(classmates[2])
print(classmates[3])
![](http://image109.360doc.com/DownloadImg/2023/02/1011/260410675_3_20230210111313661_wm.png)
当索引超出了范围时,Python会报一个IndexError错误,所以,要确保索引不要越界,记得最后一个元素的索引是len(classmates) - 1。 如果要取最后一个元素,除了计算索引位置外,还可以用-1 做索引,直接获取最后一个元素: ![](http://image109.360doc.com/DownloadImg/2023/02/1011/260410675_4_20230210111314645.png)
以此类推,可以获取倒数第2个、倒数第3个:
classmates = ['Michael', 'Bob', 'Tracy']
print(classmates[-1])
print(classmates[-2])
print(classmates[-3])
print(classmates[-4])
![](http://image109.360doc.com/DownloadImg/2023/02/1011/260410675_5_20230210111314802_wm.png)
当然,倒数第4个就越界了。 2. list是一个可变的有序表,往list中追加元素到末尾:classmates = ['Michael', 'Bob', 'Tracy']
classmates.append('Adam')
print(classmates)
也可以把元素插入到指定的位置,比如索引号为1 的位置: classmates = ['Michael', 'Bob', 'Tracy'] #替换 classmates.insert(1, 'Jack')
print(classmates)
![](http://image109.360doc.com/DownloadImg/2023/02/1011/260410675_6_20230210111315130_wm.png)
pop()函数1. 删除list末尾的元素classmates = ['Michael', 'Bob', 'Tracy']
print(classmates.pop())
print( classmates) ['Michael', 'Jack', 'Bob', 'Tracy']
![](http://image109.360doc.com/DownloadImg/2023/02/1011/260410675_7_20230210111315505_wm.png)
2. 删除指定位置的元素,用pop(i) 方法,其中i 是索引位置。
classmates.pop(1)
print(classmates)
![](http://image109.360doc.com/DownloadImg/2023/02/1011/260410675_8_20230210111315849_wm.png)
3. 把某个元素替换成别的元素,可以直接赋值给对应的索引位置:
classmates = ['Michael', 'Bob', 'Tracy']
classmates[1] = 'Sarah'
print(classmates)
![](http://image109.360doc.com/DownloadImg/2023/02/1011/260410675_9_20230210111316145_wm.png)
list里面的元素的数据类型也可以不同,比如:
list元素也可以是另一个list,比如: s = ['python', 'java', ['asp', 'php'], 'scheme'] print(len(s))
![](http://image109.360doc.com/DownloadImg/2023/02/1011/260410675_10_20230210111316364_wm.png)
要注意s 只有4个元素,其中s[2] 又是一个list,如果拆开写就更容易理解了: p = ['asp', 'php'] s = ['python', 'java', p, 'scheme']
要拿到'php' 可以写p[1] 或者s[2][1] ,因此s 可以看成是一个二维数组,类似的还有三维、四维……数组,不过很少用到。 如果一个list中一个元素也没有,就是一个空的list,它的长度为0: 二、总结本文基于Python基础,主要介绍了Python基础中list列表,通过list列表的两个函数 ,对list的语法做了详细的讲解,用丰富的案例 ,代码效果图的展示帮助大家更好理解 。 使用Python编程语言,方便大家更好理解,希望对大家的学习有帮助。 看完本文有收获?请转发分享给更多的人
IT共享之家
|