列表是python中常见的基础数据类型,下面简单介绍列表的常见操作
- 创建一个列表
list = [1, "hello", 3.0, True]
print(list)
输入结果:
[1, 'hello', 3.0, True]
- 增加一个元素
list = [1, "hello", 3.0, True]
print(list)
# 尾部插入一个元素
list.append("world")
print(list)
# 中间插入一个元素
list.insert(1, "name")
print(list)
显示结果
[1, 'hello', 3.0, True]
[1, 'hello', 3.0, True, 'world']
[1, 'name', 'hello', 3.0, True, 'world']
- 删除元素
list = [1, 'name', 'hello', 3.0, True, 'world']
list.pop(1)
print(list)
list.remove("hello")
print(list)
显示结果
[1, 'hello', 3.0, True, 'world']
[1, 3.0, True, 'world']
- 修改元素
list = [1, "hello", 3.0, True]
list[2] = "name"
print(list)
显示结果
[1, 'hello', 'name', True]
- 查询元素
list = [1, "hello", 3.0, True]
print(list[2])
显示结果
3.0
- 常用函数
# -*- coding:utf-8 -*-
# 列表长度
list = [1, "hello", 3.0, True]
l = len(list)
print("长度%d" % l)
list = [1, 2, 3, 5, 7, 0, 3, 4, 5]
# 获取最大、最小值 不支持不同类型比较
print("max:%d" % max(list))
print("min:%d" % min(list))
# 遍历5 在数组的次数
print("count:%d" % list.count(5))
print("列表中第一个5的索引%d" % list.index(5))
print("列表中第二个5的索引%d" % list.index(5, list.index(5) + 1))
# 反转
list.reverse()
print(list)
# 排序
list.sort()
print(list)
显示结果
长度4
max:7
min:0
count:2
列表中第一个5的索引3
列表中第二个5的索引8
[5, 4, 3, 0, 7, 5, 3, 2, 1]
[0, 1, 2, 3, 3, 4, 5, 5, 7]