【Python零基础入门】第10篇:Python列表方法与应用实例

学习目标

深入学习Python列表的各种方法(排序、反转、查找等),掌握列表推导式、map和filter等函数式编程技巧,通过丰富的实战案例提升列表操作能力!


导语

在上一篇中,我们学习了列表的基础操作:创建、访问、修改。今天,我们将深入探索Python列表的各种方法高级技巧

Python的列表是一个非常强大的数据结构,它提供了丰富的方法来操作数据。同时,Python还支持列表推导式这种简洁优雅的语法,让你可以用一行代码完成复杂的列表操作。

让我们一起掌握这些强大的工具,让列表操作变得更加高效!


一、列表方法概览

Python列表提供了丰富的方法,可以分为以下几类:

类别 方法 说明
添加元素 append, insert, extend 在列表末尾或指定位置添加元素
删除元素 remove, pop, clear 删除指定值或索引的元素
查找统计 index, count 查找索引、统计出现次数
排序反转 sort, reverse 排序和反转列表
复制 copy 创建列表副本

1.1 添加元素方法回顾

append - 在末尾添加单个元素

fruits = apple, banana

fruits.append(cherry)

print(fruits) # apple, banana, cherry

insert - 在指定位置插入

fruits.insert(1, blueberry)

print(fruits) # apple, blueberry, banana, cherry

extend - 批量添加(合并列表)

fruits.extend(date, fig)

print(fruits) # apple, blueberry, banana, cherry, date, fig

1.2 删除元素方法回顾

remove - 删除第一个匹配的值

numbers = 1, 2, 3, 2, 4

numbers.remove(2)

print(numbers) # 1, 3, 2, 4

pop - 删除并返回指定索引的元素(默认最后)

last = numbers.pop()

print(last) # 4

print(numbers) # 1, 3, 2

clear - 清空列表

numbers.clear()

print(numbers) # \[\]


二、列表排序

2.1 sort() 方法

sort()方法对列表进行原地排序(修改原列表)

numbers = 3, 1, 4, 1, 5, 9, 2, 6

numbers.sort()

print(numbers) # 1, 1, 2, 3, 4, 5, 6, 9

降序排序

numbers.sort(reverse=True)

print(numbers) # 9, 6, 5, 4, 3, 2, 1, 1

2.2 自定义排序(key参数)

fruits = cherry, apple, Blueberry, banana

按长度排序

fruits.sort(key=len)

print(fruits) # apple, cherry, banana, Blueberry

忽略大小写排序

fruits.sort(key=str.lower)

print(fruits) # apple, banana, Blueberry, cherry

2.3 sorted() 函数

sorted()函数返回新列表,不修改原列表

numbers = 3, 1, 4, 1, 5

sorted_numbers = sorted(numbers)

print(sorted_numbers) # 1, 1, 3, 4, 5

print(numbers) # 3, 1, 4, 1, 5 - 原列表不变

sorted同样支持reverse和key

words = Python, is, awesome

result = sorted(words, key=len, reverse=True)

print(result) # awesome, Python, is

2.4 sort() vs sorted() 对比

特性 list.sort() sorted()
返回值 None 新列表
修改原列表
适用对象 仅列表 任何可迭代对象
内存效率 高(原地排序) 低(创建新列表)

三、列表反转

3.1 reverse() 方法

reverse()方法原地反转列表

fruits = apple, banana, cherry

fruits.reverse()

print(fruits) # cherry, banana, apple

3.2 切片反转

numbers = 1, 2, 3, 4, 5

reversed_list = numbers::-1

print(reversed_list) # 5, 4, 3, 2, 1

print(numbers) # 1, 2, 3, 4, 5 - 原列表不变

3.3 reversed() 函数

返回一个反转迭代器,不创建新列表(节省内存)

numbers = 1, 2, 3, 4, 5

for num in reversed(numbers):

print(num, end= ) # 5 4 3 2 1

转回列表

reversed_list = list(reversed(numbers))

print(reversed_list) # 5, 4, 3, 2, 1

3.4 三种反转方式对比

方式 修改原列表 返回值 适用场景
list.reverse() None 需要原地反转
list::-1 新列表 需要新列表
reversed() 迭代器 只需遍历,节省内存

四、列表推导式(List Comprehension)

列表推导式是Python中最强大的特性之一,可以用一行代码创建列表

4.1 基本语法

表达式 for 变量 in 可迭代对象

传统方式

squares = \[\]

for x in range(10):

squares.append(x ** 2)

print(squares) # 0, 1, 4, 9, 16, 25, 36, 49, 64, 81

列表推导式

squares = x \*\* 2 for x in range(10)

print(squares) # 0, 1, 4, 9, 16, 25, 36, 49, 64, 81

4.2 带条件的推导式

表达式 for 变量 in 可迭代对象 if 条件

过滤偶数

evens = x for x in range(20) if x % 2 == 0

print(evens) # 0, 2, 4, 6, 8, 10, 12, 14, 16, 18

过滤 + 转换

result = x \*\* 2 for x in range(20) if x % 2 == 0

print(result) # 0, 4, 16, 36, 64, 100, 144, 196, 256, 324

4.3 嵌套推导式

创建乘法表

table = \[i \* j for j in range(1, 10) for i in range(1, 10)]

for row in table:

print(row)

输出 9x9 乘法表

4.4 多个for循环

组合两个列表

colors = red, green

items = apple, banana

combinations = f{c} {i} for c in colors for i in items

print(combinations)

red apple, red banana, green apple, green banana

4.5 推导式 vs 普通循环

特性 列表推导式 普通for循环
代码量 少(一行) 多(多行)
执行速度 相对较慢
可读性 简单场景好 复杂逻辑更清晰
适用场景 简单转换过滤 复杂操作

五、函数式编程:map和filter

5.1 map() 函数

对列表每个元素应用函数

语法:map(函数, 可迭代对象)

numbers = 1, 2, 3, 4, 5

计算平方

squares = list(map(lambda x: x ** 2, numbers))

print(squares) # 1, 4, 9, 16, 25

使用内置函数

words = hello, WORLD, Python

upper_words = list(map(str.upper, words))

print(upper_words) # HELLO, WORLD, PYTHON

多个可迭代对象

list1 = 1, 2, 3

list2 = 10, 20, 30

sums = list(map(lambda x, y: x + y, list1, list2))

print(sums) # 11, 22, 33

5.2 filter() 函数

过滤列表元素

语法:filter(函数, 可迭代对象) - 保留函数返回True的元素

numbers = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

过滤偶数

evens = list(filter(lambda x: x % 2 == 0, numbers))

print(evens) # 2, 4, 6, 8, 10

过滤非空字符串

words = hello, , world, , python

non_empty = list(filter(None, words))

print(non_empty) # hello, world, python

5.3 map/filter vs 列表推导式

map + filter 组合

numbers = range(20)

result = list(map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, numbers)))

等价的列表推导式(更简洁)

result = x \*\* 2 for x in range(20) if x % 2 == 0

两者结果相同:0, 4, 16, 36, 64, 100, 144, 196, 256, 324

**建议:**简单操作优先使用列表推导式,复杂逻辑可使用map/filter


六、其他实用技巧

6.1 enumerate() 枚举

同时获取索引和值

fruits = apple, banana, cherry

for index, fruit in enumerate(fruits):

print(f{index}: {fruit})

0: apple

1: banana

2: cherry

指定起始索引

for index, fruit in enumerate(fruits, start=1):

print(f{index}. {fruit})

1. apple

2. banana

3. cherry

6.2 zip() 打包多个列表

names = Alice, Bob, Charlie

ages = 25, 30, 35

cities = NYC, LA, Chicago

for name, age, city in zip(names, ages, cities):

print(f{name}, {age}岁, {city})

长度不一致时,以最短为准

list1 = 1, 2, 3

list2 = a, b

print(list(zip(list1, list2))) # (1, a), (2, b)

6.3 any() 和 all()

any() - 任一元素为真则返回True

numbers = 0, 0, 1, 0

print(any(numbers)) # True

all() - 所有元素为真才返回True

numbers = 1, 2, 3, 4

print(all(numbers)) # True

实际应用

scores = 85, 90, 78, 92

是否全部及格

all_pass = all(s >= 60 for s in scores)

是否有优秀

has_excellent = any(s >= 90 for s in scores)

6.4 sum(), min(), max()

numbers = 3, 1, 4, 1, 5

print(sum(numbers)) # 14

print(min(numbers)) # 1

print(max(numbers)) # 5

sum的初始值

print(sum(numbers, 100)) # 114(从100开始加)


七、实战案例

7.1 数据处理流水线

原始数据

raw_data = 100, 200, N/A, 300, invalid, 400, , 500

清理数据:提取数字

cleaned = \[\]

for item in raw_data:

try:

num = int(item)

cleaned.append(num)

except (ValueError, TypeError):

pass

print(cleaned) # 100, 200, 300, 400, 500

使用列表推导式(更简洁)

cleaned = int(x) for x in raw_data if isinstance(x, (int, str)) and str(x).isdigit()

7.2 学生成绩统计

students = [

{name: Alice, scores: 85, 90, 88},

{name: Bob, scores: 78, 82, 80},

{name: Charlie, scores: 92, 95, 94}

]

计算平均分并排序

averages = [

{name: sname, avg: sum(sscores) / len(sscores)}

for s in students

]

averages.sort(key=lambda x: xavg, reverse=True)

for student in averages:

print(f{studentname}: {studentavg:.2f})

7.3 扁平化嵌套列表

将嵌套列表展开为一维列表

nested = \[1, 2, 3, 4, 5, 6, 7, 8, 9]

方法1:使用推导式

flat = item for sublist in nested for item in sublist

print(flat) # 1, 2, 3, 4, 5, 6, 7, 8, 9

方法2:使用sum(不推荐大数据量)

flat = sum(nested, \[\])

方法3:使用itertools

import itertools

flat = list(itertools.chain.from_iterable(nested))

7.4 查找最值及索引

scores = 85, 92, 78, 95, 88, 91

找最大值及其索引

max_score = max(scores)

max_index = scores.index(max_score)

print(f最高分:{max_score},位置:{max_index})

找最小值及其索引

min_score = min(scores)

min_index = scores.index(min_score)

print(f最低分:{min_score},位置:{min_index})

找前3名(排序后取前3)

top3 = sorted(scores, reverse=True):3

print(f前3名:{top3})

7.5 列表去重并保持顺序

def unique_ordered(items):

seen = set()

result = \[\]

for item in items:

if item not in seen:

seen.add(item)

result.append(item)

return result

numbers = 1, 2, 2, 3, 3, 3, 4, 2, 1

print(unique_ordered(numbers)) # 1, 2, 3, 4

Python 3.7+ 简洁写法

def unique_ordered_v2(items):

return list(dict.fromkeys(items))

7.6 旋转列表

def rotate_left(lst, k):

向左旋转k位

k = k % len(lst) # 处理k大于长度的情况

return lstk: + lst:k

def rotate_right(lst, k):

向右旋转k位

k = k % len(lst)

return lst-k: + lst:-k

numbers = 1, 2, 3, 4, 5

print(rotate_left(numbers, 2)) # 3, 4, 5, 1, 2

print(rotate_right(numbers, 2)) # 4, 5, 1, 2, 3

7.7 分组

将列表按指定大小分组

def chunk(lst, size):

return lst\[i:i+size for i in range(0, len(lst), size)]

numbers = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

print(chunk(numbers, 3))

\[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


八、小结

今天我们深入学习了Python列表的各种方法和高级技巧:

**✅ 列表方法:**sort/sorted排序、reverse反转、index查找、count统计

✅ 列表推导式:x for x in iterable if condition

**✅ 函数式编程:**map、filter、lambda表达式

**✅ 实用函数:**enumerate、zip、any、all、sum、min、max

**✅ 实战技巧:**数据处理、扁平化、去重、旋转、分组

💡 性能建议:

  1. 简单操作优先使用列表推导式,代码更简洁高效

  2. 大数据量时,使用生成器表达式替代列表推导式节省内存

  3. sort()原地排序比sorted()更高效(不需要创建新列表)

  4. 需要同时遍历索引和值时,使用enumerate()

  5. 多个列表并行遍历时,使用zip()


九、课后练习与答案

练习1:排序

题目:

words = python, java, C++, javascript, go

  1. 按字母顺序排序(不区分大小写)

  2. 按字符串长度排序

  3. 获取排序后的新列表(不修改原列表)

答案:

words = python, java, C++, javascript, go

1. 按字母排序(不区分大小写)

words.sort(key=str.lower)

print(words) # C++, go, java, javascript, python

2. 按长度排序

words.sort(key=len)

print(words) # go, C++, java, python, javascript

3. 获取新列表

sorted_words = sorted(words)

print(sorted_words) # 新列表

print(words) # 原列表不变

练习2:列表推导式

题目:

  1. 创建1-100中能被3整除的数的列表

  2. 将字符串列表转为大写:words = hello, world

  3. 提取嵌套列表的所有偶数:nested = \[1, 2, 3, 4, 5, 6]

答案:

1. 能被3整除

result = x for x in range(1, 101) if x % 3 == 0

print(result) # 3, 6, 9, ... 99

2. 转为大写

words = hello, world

upper_words = w.upper() for w in words

print(upper_words) # HELLO, WORLD

3. 提取偶数

nested = \[1, 2, 3, 4, 5, 6]

evens = x for sub in nested for x in sub if x % 2 == 0

print(evens) # 2, 4, 6

练习3:map和filter

题目:

numbers = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

  1. 使用map计算每个数的平方

  2. 使用filter过滤出奇数

  3. 组合map和filter:先过滤偶数,再计算平方

答案:

numbers = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

1. 计算平方

squares = list(map(lambda x: x ** 2, numbers))

print(squares) # 1, 4, 9, 16, 25, 36, 49, 64, 81, 100

2. 过滤奇数

odds = list(filter(lambda x: x % 2 == 1, numbers))

print(odds) # 1, 3, 5, 7, 9

3. 组合使用

result = list(map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, numbers)))

print(result) # 4, 16, 36, 64, 100

更简洁的写法(列表推导式)

result = x \*\* 2 for x in numbers if x % 2 == 0

练习4:enumerate和zip

题目:

names = Alice, Bob, Charlie

scores = 85, 90, 78

  1. 使用enumerate打印带序号的学生名单

  2. 使用zip将姓名和分数对应起来

  3. 找出分数最高的学生

答案:

names = Alice, Bob, Charlie

scores = 85, 90, 78

1. 带序号

for i, name in enumerate(names, 1):

print(f{i}. {name})

2. 对应起来

for name, score in zip(names, scores):

print(f{name}: {score})

3. 找最高分

max_score = max(scores)

max_index = scores.index(max_score)

print(f最高分:{namesmax_index} - {max_score})

练习5:any和all

题目:

scores = 85, 90, 55, 78, 92

  1. 判断是否全部及格(>=60)

  2. 判断是否有优秀(>=90)

  3. 判断是否有不及格

答案:

scores = 85, 90, 55, 78, 92

1. 全部及格

all_pass = all(s >= 60 for s in scores)

print(f全部及格:{all_pass}) # False

2. 有优秀

has_excellent = any(s >= 90 for s in scores)

print(f有优秀:{has_excellent}) # True

3. 有不及格

has_fail = any(s < 60 for s in scores)

print(f有不及格:{has_fail}) # True

练习6:综合练习

题目:

给定字符串列表,要求:

  1. 过滤掉长度小于3的字符串

  2. 将剩余字符串转为大写

  3. 按字母顺序排序

  4. 用一行代码完成

答案:

words = hi, hello, a, python, go, world, code

一行代码

result = sorted(w.upper() for w in words if len(w) \>= 3)

print(result) # CODE, HELLO, PYTHON, WORLD

分步写法

filtered = w for w in words if len(w) \>= 3 # hello, python, world, code

uppered = w.upper() for w in filtered # HELLO, PYTHON, WORLD, CODE

result = sorted(uppered) # CODE, HELLO, PYTHON, WORLD


十、下篇预告

第11篇:《Python元组:不可变序列的使用场景》

在下一篇中,我们将学习Python的另一个重要序列类型------元组:

  • 元组的创建和基本操作

  • 元组与列表的区别

  • 元组的不可变性

  • 元组的性能优势

  • 元组的使用场景

  • 元组解包

敬请期待!


系列文章目录:点击关注,持续更新中...

VIP专属:加入VIP,获取更多进阶内容和完整源码!


如果觉得有帮助,请点赞 + 收藏 + 关注

你的支持是我持续创作的动力!


本文为本系列第10篇,带你从零基础到Python实战!

相关推荐
下午写HelloWorld1 小时前
同态加密(Homomorphic Encryption, HE)
人工智能·算法·密码学·同态加密
Kobebryant-Manba1 小时前
安装cuda
pytorch·python·深度学习·conda·numpy
尚可签1 小时前
小烟改写工具:让文字表达更自然,让文档改写更高效
人工智能
CC数学建模1 小时前
2026第八届中青杯全国大学生数学建模竞赛B题:AI生成内容的质量评估与参数优化完整思路、代码、模型、文章,全网首发高质量分享!
python·算法·数学建模
神仙别闹1 小时前
基于 Python 实现 ANN 与 KNN 的图像分类
开发语言·python·分类
聚名网1 小时前
中文域名深化实体应用,稳步对接智能交互场景
人工智能·经验分享
极客笔记Jack1 小时前
Scanpy 高级可视化:从默认配色到发表级图表
python
SilentSamsara1 小时前
高并发 API 压测与调优:locust + 火焰图 + 瓶颈定位
开发语言·python·青少年编程·docker·中间件
决战灬1 小时前
llamaIndex BatchEvalRunner(一)
人工智能