Python列表
列表操作
定义:list(此处为列表名字) = [(这里写列表元素,用" "包含,逗号隔开,如)“a”,“b”]
students = [“Linda”,“bob”,“Alice”,“Alen”]
通过下标可以访问列表的值。从0开始计数。
students[0] -------> linda
students[1] -------> bob
students[2] -------> Alice
students[3] -------> lAlen
列表切片操作:
students = [“Linda”,“bob”,“Alice”,“Alen”,“John”]
students[1:4] #取下标1至下标4之间的值,包括1不包括4
students[1:-1] #取下标1至下标-1之间的值,包括1不包括-1
students[0:3] #取下标0至下标3之间的值,包括0不包括3
students[:3] = students[0:3] #从0开始,0可以忽略
students[4:] #取列表最后一个元素,只能写最后一个开始,不可以写-1
students[0:] students[:] #取列表中所有元素
students[2:-1] #-1没有包含
students[0::2] #表示每间隔一个元素取一个
students[::2] #0可以省略
列表末尾追加元素:
students = [“Linda”,“bob”,“Alice”,“Alen”,“John”]
students.append(" 我是新同学")
列表中插入元素:insert
students.insert(2,“小明”) #在第2个位置插入小明,其他元素向后移动一位
[“Linda”,“bob”,“小明”,“Alice”,“Alen”,“John”]
students.insert(5,“小李”) #在第5个位置插入小李,其他元素向后移动一位
[“Linda”,“bob”,“小明”,“Alice”,“Alen”,“小李”,“John”]
修改列表元素:
只需要修改对应位置的值就可以
students = ["Alice","Linda","bob","Alice","Alen","John"]
print(students)
students[2] = "Bob"
print(students)
删除列表元素:有三种删除列表元素的方法
1.del
2.remove
3.pop
students = ["Alice","Linda","bob","Alice","Alen","John"]
del students[1] #删除对应下标的元素
print(students)
students.remove("Alen") #删除指定元素
print(students)
students.pop() #删除列表最后一个元素
print(students)
列表扩展:
列表扩展指令为extend
students = ["Alice","Linda","bob","Alice","Alen","John"]
print(students)
studentsnumber = [1,2,3,4,5]
students.extend(studentsnumber)
print(students)
*
列表拷贝:
*copy,深copy,浅copy等前面博文已写,不再赘述
统计(计数):count 计算列表中同一个元素出现的次数
students = ["Alice","Linda","bob","Alice","Alen","John","Alice"]
print(students.count("Alice"))
print(students.count("bob"))
排序&翻转
sort,reverse
students = ["Alice","Linda","bob","Alice","Alen","John","Alice","!","1","2","4","3"]
print(students)
students.sort() #python3.0不支持不同元素类型的数据排序,会报错,后面的数字和标点应 该加“”
print(students)
students.reverse()
print(students)
获取元素下标:
students = ["Alice","Linda","bob","Alice","Alen","John","Alice","!","1","2","4","3"]
print(students.index("bob"))
print(students.index("Alice")) #有多个元素,只会显示第一个元素的下标