1.创建一个列表
list1 = ['Google', 'Runoob', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"];
2.查看列表中的值--运用索引
list1 = ['Google', 'Runoob', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])
输出结果:
从索引位置0开始,5结束
3.列表--增
(1)append()方法--在列表末尾追加一个元素
list1 = ['a','b','c','d']
list1.append(1,'e')
print(list1)
输出结果:['a','b','c','d','e']
(2)insert()方法--插入指定位置的元素
list1 = ['a','b','c','d']
list1.insert(1,'e')
print(list1)
输出结果:['a', 'e', 'b', 'c', 'd']
(3)extend()方法--把另一个列表加入到指定列表末尾
list1 = ['a','b','c','d']
list2 = ['e','f','g']
list1.extend(list2)
print(list1)
输出结果:['a', 'b', 'c', 'd', 'e', 'f', 'g']
4.列表--删
(1)clear()方法--清空整个列表
(2)1.pop()方法--弹出列表末尾的元素,弹出的值仍然可以使用
2.pop()方法--弹出指定位置的元素,弹出的值仍然可以使用
(3)remove()方法--移除:根据值删除元素
(4)del 语句--直接删除
Python列表函数&方法
函数:
(1)len(list)--列表元素个数
(2)max(list)--返回列表元素最大值
(3)min(list)--返回列表元素最小值
(4)list(seq)--将元组转换成列表
方法:
序号 | 方法 |
---|---|
1 | list.append(obj) 在列表末尾添加新的对象 |
2 | list.count(obj) 统计某个元素在列表中出现的次数 |
3 | list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) |
4 | list.index(obj) 从列表中找出某个值第一个匹配项的索引位置 |
5 | list.insert(index, obj) 将对象插入列表 |
6 | list.pop(obj=list[-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 |
7 | list.remove(obj) 移除列表中某个值的第一个匹配项 |
8 | list.reverse() 反向列表中元素 |
9 | list.sort([func]) 对原列表进行排序 |
10 | list.clear() 清空列表 |
11 | list.copy() 复制列表 |
部分参考“菜鸟教程”:http://www.runoob.com/python3/python3-list.html