python3编程实练-熟悉列表(list)常见操作
list.py:
# -*- coding: utf-8 -*-
import operator
# 函数定义
def f():
# 列表赋值
list = [1, 2, 3, 4, 5]
print(list)
# 列表赋值
list = ["tom", "steven", "smith"]
print(list)
# 获取列表长度
print(len(list))
# 获取列表最大值 / 最小值
print(max(list))
print(min(list))
# 列表索引
print(list[1])
# 列表切片
print(list[0:2])
# 列表更新
list[0] = "test"
list.append("joe")
# 列表插入
list.insert(1, "xxx")
# 列表删除
del list[2]
list.remove("test")
# 移除列表中的最后一个元素
list.pop()
#清空列表
list.clear()
# 列表组合
list = [1, 2, 3] + [4, 5, 6]
print(list)
# 列表重复
list = [1, 2] * 3
print(list)
# 列表复制
print(list.copy())
# 判断元素是否存在
print(1 in list)
print(list.index(1))
# 获取元素在列表中出现的次数
print(list.count(1))
# 列表遍历
for v in list:
print(v)
# 列表排序
list.sort()
# 列表反向
list.reverse()
# 列表比较
list1 = [1, 2]
list2 = [1, 2]
list3 = [2, 3]
print(operator.eq(list1, list2))
print(operator.eq(list1, list3))
if __name__ == '__main__':
f()
运行:
(.venv) PS > python list.py
[1, 2, 3, 4, 5]
['tom', 'steven', 'smith']
3
tom
smith
steven
['tom', 'steven']
[1, 2, 3, 4, 5, 6]
[1, 2, 1, 2, 1, 2]
[1, 2, 1, 2, 1, 2]
True
0
3
1
2
1
2
1
2
True
False
说明:
- 列表类型在写python代码时,跟字符串类型类似,几乎随时都需要用到。因此整体过一遍python中列表操作,成为必要。
- python中列表类型的操作还是很丰富的。
- python中变量的类型是根据内容的类型决定的,因此列表的元素可以是同一个类型的(这是最常见的),也可以是不同类型的(你可以理解成any类型)