Python列表
序列是Python中最基本的数据结构。序列中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。
Python有6个序列的内置类型,但最常见的是列表和元组
创建一个列表,只要把逗号分隔的不同的数据项使用方括号括起来即可。如下所示:
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]
1、访问列表中的值
print( "list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])
以上实例输出结果:
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
2、更新列表
list = []#空列表
list.append('Google') # 使用 append() 添加元素
list.append('Runoob')
print (list)
输出结果 :['Google', 'Runoob']
3、删除元素
list1 = ['physics', 'chemistry', 1997, 2000]
print(list1)
del list1[2]
print("After deleting value at index 2 : ")
print(list1)
输出结果:
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]
4、Python列表函数&方法
len(list) 列出列表元素的个数
max(list)列车列表中元素最大值
min(list)列车列表中元素最小值
方法:
list.append() 在列表末尾添加新的对象
list.count(obj)统计某个元素在列表中出现的次数
list.pop(index=-1)移除列表中的一个元素(默认最后一个元素),并返回该元素的值
list.remove(obj) 移除列表中某个值的第一个匹配项
list.reverse() 反向列表中元素