「Python教案」通用序列操作

97 阅读9分钟

课程目标

1. 知识目标

  1. 能够正确使用Python中通用序列操作,例如,索引、切片、连接、重复、成员检测、长度计算等。
  2. 能够正确将序列操作应用在实际数据处理的中场景。

2 能力目标

  1. 能独立编写序列操作代码并进行调试,解决实际问题。
  2. 能对错误代码进行分析,并优化代码逻辑。

3 思政目标

  1. 通过序列操作的严谨性,培养“细节决定成败”的工匠精神。
  2. 结合数据处理的实际应用,渗透“技术服务于社会”的职业责任感。

教学内容

1. 通用序列操作类型

  1. 索引操作
  • 基本语法:sequence[index]。
  • 支持正向索引和反向索引。正向索引,从左到右,从0开始。反向索引,从右到左,从-1开始。
  • 适用于字符串、列表、元组、字节等序列类型。
  • 示例:s = "Python" → s[0] → 'P';s[-1] → 'n'
  1. 切片操作
  • 基本语法:sequence[start:stop:step]。
  • 切片规则:start包含,stop不包含;步长为负时方向反转。
  • 步长为负时,start需大于stop,否则返回空序列。
  • 支持省略,例如,[:]获得整个序列;负步长,例如,[::-1]实现反转。
  • 适用于字符串、列表、元组、字节等序列类型。
  • 示例:lst = [1,2,3,4] → lst[1:3] → [2,3];s[::-1] → 'nohtyP'
  1. 连接操作
  • 基本语法:sequence1 + sequence2,要求两侧类型一致。
  • 适用于字符串、列表、元组(不可变类型需重新赋值)等序列类型。
  • 示例:[1,2] + [3,4] → [1,2,3,4];'Hello' + ' ' + 'World' → 'Hello World'
  1. 重复操作
  • 基本语法:sequence * n,要求右侧为整数。
  • 适用于字符串、列表、元组等序列类型。
  • 示例:'Hi' * 3 → 'HiHiHi';[0] * 5 → [0,0,0,0,0]
  1. 成员检测操作
  • 基本语法:value in sequence 或 value not in sequence,返回布尔值。
  • 适用于字符串、列表、元组等序列类型。
  • 示例:'a' in 'apple' → True;5 not in [1,2,3] → True。
  1. 长度计算
  • 基本语法:len(sequence),返回序列元素数量。
  • 在编写程序时使用len()验证索引范围。
  • 适用于字符串、列表、元组等序列类型。
  • 示例:len('Python') → 6;len([]) → 0。

2.多种 类型序列的通用性验证

# 字符串
s = "Data"
print(s[1:3])  # 输出: 'at'
print('a' in s)  # 输出: True

# 列表
lst = [10, 20, 30]
print(lst[1:3])  # 输出: [20, 30]
print(20 in lst)  # 输出: True

# 元组
tup = (100, 200, 300)
print(tup[1:3])  # 输出: (200, 300)
print(400 not in tup)  # 输出: True

运行结果

at

True

[20, 30]

True

(200, 300)

True



进程已结束,退出代码为 0

说明:索引、切片、成员检测等操作在字符串、列表、元组中使用方法是一致的。

重点分析

​编辑

难点分析

​编辑

教学活动设计

概念引入

序列数据好比“超市货架”。

  1. 索引类似于货架编号,如第1层、第-1层。
  2. 切片类似于取连续商品,如“第2到第4层”。
  3. 连接类似于将多个货架合并。
  4. 重复类似于将货架中的货物复制多份。

示例:

fruits = ['apple', 'banana', 'cherry']
print(fruits[0])  # 索引:取第一个元素
print(fruits[-1])  # 反向索引:取最后一个元素
print(fruits[1:3])  # 切片:取索引1到2的元素

运行结果

apple

cherry

['banana', 'cherry']



进程已结束,退出代码为 0

索引与切片

s = "ABCDEFG"
for i in range(-len(s), len(s)):
    print(f"s[{i}] = {s[i] if 0 <= i < len(s) else 'Out of range'}")

运行结果

s[-7] = Out of range

s[-6] = Out of range

s[-5] = Out of range

s[-4] = Out of range

s[-3] = Out of range

s[-2] = Out of range

s[-1] = Out of range

s[0] = A

s[1] = B

s[2] = C

s[3] = D

s[4] = E

s[5] = F

s[6] = G



进程已结束,退出代码为 0

案例解析

**案例: **统计字符串中元音字母数量

text = "Python is powerful"
vowels = "aeiou"
count = sum(1 for char in text if char.lower() in vowels)
print(count)  # 输出:5

运行结果

5



进程已结束,退出代码为 0

**案例: **列表切片反转

nums = [1, 2, 3, 4, 5]
reversed_nums = nums[::-1]
print(reversed_nums)  # 输出:[5, 4, 3, 2, 1]

运行结果

[5, 4, 3, 2, 1]



进程已结束,退出代码为 0

**案例: **统计单词频率

text = "apple banana apple orange banana apple"
words = text.split()
word_counts = {}
for word in words:
    word_counts[word] = word_counts.get(word, 0) + 1
print(word_counts)  # 输出: {'apple': 3, 'banana': 2, 'orange': 1}

运行结果

{'apple': 3, 'banana': 2, 'orange': 1}



进程已结束,退出代码为 0

常见错误

**错误: **索引越界

s = "Hi"
print(s[5])  # 抛出 IndexError

运行结果

Traceback (most recent call last):

  File "D:\PythonProject\test.py", line 2, in <module>

    print(s[5])  # 抛出 IndexError

          ~^^^

IndexError: string index out of range

解决方法 ** **使用try-except或len()动态检查。修改代码如下

s = "Hi"
index = 5
if 0 <= index < len(s):
    print(s[index])
else:
    print("索引超出范围")

运行结果

索引超出范围



进程已结束,退出代码为 0

**错误: **类型不匹配

lst = [1, 2]
print(lst + "3")  # 抛出 TypeError(列表与字符串不可直接连接)

运行结果

Traceback (most recent call last):

  File "D:\PythonProject\test.py", line 2, in <module>

    print(lst + "3")  # 抛出 TypeError(列表与字符串不可直接连接)

          ~~~~^~~~~

TypeError: can only concatenate list (not "str") to list



进程已结束,退出代码为 1

解决方法 ** **强制类型转换

lst = [1, 2]
print(str(lst) + "3")  # 输出: "[1, 2]3"

运行结果

[1, 2]3



进程已结束,退出代码为 0

**错误: **切片步长为0

s = "abc"
print(s[::0])  # 抛出 ValueError(步长必须为非零整数)

运行结果

Traceback (most recent call last):

  File "D:\PythonProject\test.py", line 2, in <module>

    print(s[::0])  # 抛出 ValueError(步长必须为非零整数)

          ~^^^^^

ValueError: slice step cannot be zero



进程已结束,退出代码为 1

**错误: **混淆+与append()

lst = [1, 2]
lst + 3  # 抛出 TypeError(列表与整数不可直接连接)
lst.append(3)  # 正确:修改原列表

应用场景

**场景: **数据清洗,从日志中提取特定字段

log = "2025-05-01 INFO User logged in"
parts = log.split()  # 分割为列表
print(parts[1:3])  # 输出: ['INFO', 'User']

运行结果

['INFO', 'User']



进程已结束,退出代码为 0

**场景: **字符串反转

print("Python"[::-1])  # 输出: "nohtyP"

运行结果

nohtyP



进程已结束,退出代码为 0

**场景: **列表重复与扩展

print([1, 2, 3] * 3)  # 输出: [1, 2, 3, 1, 2, 3, 1, 2, 3]

运行结果

[1, 2, 3, 1, 2, 3, 1, 2, 3]



进程已结束,退出代码为 0

课堂练习

**练习: **从字符串"Hello World"中提取"World"。

**答案: **text[6:11]

**练习: **将列表[1, 2, 3]重复3次并连接成字符串。

**答案: **str([1, 2, 3] * 3)[1:-1],输出:"1, 2, 3, 1, 2, 3, 1, 2, 3"

**练习: **从version字符串"Python3.8"中提取版本号"3.8"。

**答案: **version = s[6:]

**练习: **用切片将result列表[0, 1, 2, 3, 4, 5]转换为[5, 3, 1]。

**答案: **result = lst[5::-2]

课后作业

**作业: **用切片反转元组(10, 20, 30, 40)。

**答案: **tuple_reversed = (10, 20, 30, 40)[::-1]。

**作业: **编写程序,统计字符串中每个字符的出现次数,要求忽略大小写。

s = "hello python"
s = s.lower()
char_count = {}
for char in s:
    if char.isalpha():  # 仅统计字母
        char_count[char] = char_count.get(char, 0) + 1
print(char_count)

运行结果

{'h': 2, 'e': 1, 'l': 2, 'o': 2, 'p': 1, 'y': 1, 't': 1, 'n': 1}



进程已结束,退出代码为 0

**作业: **编写程序,将字符串中的元音字母替换为'*'。

s = "Hello Python Programming"
vowels = "aeiouAEIOU"
print( ''.join(['*' if c in vowels else c for c in s]))

运行结果

H*ll* Pyth*n Pr*gr*mm*ng



进程已结束,退出代码为 0

考核设计

1 过程性考核(40%)

  1. 课堂练习的完成程度(20%)
  2. 编写代码的规范性与添加注释的规范性(10%)
  3. 参与小组讨论和解决问题的能力(10%)

2 终结性考核(60%)

  1. 理论测试(20%):选择题。
  2. 综合项目(40%):学生成绩管理系统。

**综合项目: **学生成绩管理系统,要求使用列表的基本操作实现以下功能:

  1. 创建一个空列表存储学生成绩
  2. 添加5个学生成绩(成绩为0-100的整数)
  3. 计算并输出平均成绩
  4. 找出并输出最高分和最低分
  5. 将成绩从高到低排序并输出
  6. 检查是否有成绩等于100分
  7. 将及格成绩(≥60)筛选出来存入新列表
# 1. 创建空列表
scores = []

# 2. 添加5个学生成绩
scores.append(85)
scores.append(92)
scores.append(78)
scores.append(60)
scores.append(100)

# 3. 计算平均成绩
average = sum(scores) / len(scores)
print(f"平均成绩: {average:.1f}")

# 4. 找出最高分和最低分
max_score = max(scores)
min_score = min(scores)
print(f"最高分: {max_score}, 最低分: {min_score}")

# 5. 成绩从高到低排序
sorted_scores = sorted(scores, reverse=True)
print("成绩排序:", sorted_scores)

# 6. 检查是否有满分
has_full_score = 100 in scores
print("是否有满分:", "有" if has_full_score else "无")

# 7. 筛选及格成绩
passing_scores = [score for score in scores if score >= 60]
print("及格成绩:", passing_scores)

运行结果

平均成绩: 83.0

最高分: 100, 最低分: 60

成绩排序: [100, 92, 85, 78, 60]

是否有满分: 有

及格成绩: [85, 92, 78, 60, 100]



进程已结束,退出代码为 0