|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
append()函数
在列表中添加新元素时,最简单的方法就是附加在末尾:
- list_1 = ['one', 'two', 'three']
- print(list_1)
- list_1.append('four')
- print(list_1)
复制代码
函数append()就是将'four'添加在列表末尾,而且不影响列表其他元素
- ['one', 'two', 'three']
- ['one', 'two', 'three', 'four']
复制代码
insert()函数
insert()函数顾名思义"插入",可以在列表任何位置插入元素,
insert(索引,元素),列表里元素的索引(位置)和C语言一样是从0开始的
- list_1 = ['one', 'two', 'three']
- list_1.insert(3, 'four')
- print(list_1)
复制代码- ['one', 'two', 'three', 'four']
复制代码
如果该位置上已经有元素了,那么该元素以及后面的元素会右移一位,如:  
- list_1 = ['one', 'two', 'three']
- list_1.insert(1, 'four')
- print(list_1)
复制代码- ['one', 'four', 'two', 'three']
复制代码
本来'two'元素在列表list_1索引1的位置,但是'four'插入到了1的位置,那么'two'以及后面的'three'就会右移一位 |
|