Python学不会来打我(64)python列表最常用的操作方法汇总
在 Python 编程中,列表(list) 是最常用的数据结构之一。它是一种可变、有序、可重复元素的集合,非常适合用来处理动态数据。
作为 Python 初学者,掌握列表的各种常用操作方法是学习编程的基础。本文将以图片的形式对 Python 列表 list 的最常用方法进行汇总,并通过丰富的代码示例说明其用途,帮助你快速入门并熟练运用这一重要工具。#python##python教程##python自学#
点赞、收藏、加关注,下次找我不迷路
一,python列表的切片
切片语法:list[start:end:step]
letters = ['a', 'b', 'c', 'd', 'e', 'f']
# 获取前三个元素
print(letters[:3]) # ['a', 'b', 'c']
# 获取从第2个到最后一个
print(letters[2:]) # ['c', 'd', 'e', 'f']
# 获取倒数两个元素
print(letters[-2:]) # ['e', 'f']
# 步长为2获取元素
print(letters[::2]) # ['a', 'c', 'e']
二,python列表元素的插入和删除
三,python列表元素的查找和遍历
四,python列表元素的排序
五,python列表元素的append()与extend()方法区别
六,python列表在项目开发中的常见应用场景
场景 1:学生管理系统 —— 存储和管理学生信息
students = []
def add_student(name, age):
students.append({'name': name, 'age': age})
add_student('张三', 20)
add_student('李四', 22)
for student in students:
print(student)
输出:
{'name': '张三', 'age': 20}
{'name': '李四', 'age': 22}
场景 2:电商购物车 —— 实现商品增删查改
cart = []
def add_product(product):
cart.append(product)
def remove_product(product):
if product in cart:
cart.remove(product)
add_product('手机')
add_product('耳机')
remove_product('耳机')
print(cart) # 输出: ['手机']
场景 3:数据分析 —— 对一组数值进行统计分析
scores = [90, 85, 92, 88, 95]
average = sum(scores) / len(scores)
highest = max(scores)
lowest = min(scores)
print(f"平均分: {average:.2f}")
print(f"最高分: {highest}")
print(f"最低分: {lowest}")
输出:
平均分: 90.00
最高分: 95
最低分: 85
场景 4:文件读取 —— 将文本文件每一行存入列表
with open('data.txt', 'r') as f:
lines = f.readlines()
print(lines) # 输出每行内容组成的列表