Python集合遍历案例如何循环读取

wen python案例 32

本文目录导读:

Python集合遍历案例如何循环读取

  1. 基础for循环遍历
  2. 带索引的遍历(使用enumerate)
  3. 使用while循环遍历
  4. 条件筛选遍历
  5. 嵌套集合遍历
  6. 多集合并行遍历
  7. 实际应用案例
  8. 高级技巧
  9. 性能优化建议
  10. 常见错误处理

我来给你详细讲解Python集合的多种遍历方法,包含具体案例。

基础for循环遍历

# 创建示例集合
fruits = {'apple', 'banana', 'orange', 'grape', 'mango'}
# 基础遍历
print("基础遍历:")
for fruit in fruits:
    print(fruit)
# 输出(顺序不确定,因为集合无序):
# banana
# orange
# mango
# grape
# apple

带索引的遍历(使用enumerate)

colors = {'red', 'blue', 'green', 'yellow'}
# 使用enumerate获取索引和值
print("带索引遍历:")
for index, color in enumerate(colors):
    print(f"索引 {index}: {color}")
# 输出示例(顺序随机):
# 索引 0: blue
# 索引 1: green
# 索引 2: red
# 索引 3: yellow

使用while循环遍历

# 先将集合转为列表,因为集合不支持索引访问
numbers = {1, 2, 3, 4, 5}
num_list = list(numbers)
i = 0
print("while循环遍历:")
while i < len(num_list):
    print(f"第{i+1}个元素: {num_list[i]}")
    i += 1

条件筛选遍历

# 遍历并筛选特定元素
numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
print("筛选偶数:")
even_numbers = [num for num in numbers if num % 2 == 0]
for num in even_numbers:
    print(num)

嵌套集合遍历

# 集合中包含元组
students = {('Tom', 18), ('Jerry', 19), ('Alice', 20), ('Bob', 17)}
print("遍历包含元组的集合:")
for name, age in students:
    print(f"姓名: {name}, 年龄: {age}")
# 或者使用索引
for student in students:
    print(f"学生: {student[0]}, 年龄: {student[1]}")

多集合并行遍历

set1 = {'a', 'b', 'c'}
set2 = {1, 2, 3}
# 使用zip并行遍历
print("并行遍历两个集合:")
for char, num in zip(set1, set2):
    print(f"{char} - {num}")
# 使用enumerate和zip组合
print("\n带索引的并行遍历:")
for i, (char, num) in enumerate(zip(set1, set2)):
    print(f"位置{i}: {char} - {num}")

实际应用案例

案例1:去除重复并处理数据

# 处理用户输入的用户名
usernames = ['alice', 'bob', 'alice', 'charlie', 'bob', 'david']
unique_users = set(usernames)
print("唯一用户处理:")
for user in unique_users:
    # 处理每个用户
    processed_name = user.capitalize()
    print(f"处理后的用户名: {processed_name}")

案例2:集合运算与遍历

# 学生选课系统
course_a = {'Alice', 'Bob', 'Charlie', 'David'}
course_b = {'Bob', 'David', 'Eve', 'Frank'}
print("A班学生:")
for student in course_a:
    print(f"  - {student}")
print("\n两班都选的学生:")
both = course_a & course_b  # 交集
for student in both:
    print(f"  - {student}")
print("\n只选A班的学生:")
only_a = course_a - course_b  # 差集
for student in only_a:
    print(f"  - {student}")

高级技巧

使用生成器表达式

numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
# 使用生成器高效遍历
squared_gen = (x**2 for x in numbers)
print("平方值(生成器):")
for value in squared_gen:
    print(value, end=' ')

条件过滤与处理

# 复杂条件处理
data = {15, 23, 45, 67, 89, 12, 34, 56, 78}
print("处理数据:")
for num in data:
    if num > 50:
        result = "大数"
    elif num > 20:
        result = "中数"
    else:
        result = "小数"
    print(f"{num}: {result}")

性能优化建议

import time
# 大数据集遍历优化
big_set = set(range(1000000))
# 不好的做法:多次转换
start = time.time()
for item in list(big_set):  # 不必要地创建列表
    pass
print(f"列表转换遍历耗时: {time.time() - start}")
# 好的做法:直接遍历
start = time.time()
for item in big_set:  # 直接遍历集合
    pass
print(f"直接遍历耗时: {time.time() - start}")

常见错误处理

# 遍历时修改集合的错误
numbers = {1, 2, 3, 4, 5}
# 错误方式:遍历时直接修改
try:
    for num in numbers:
        if num % 2 == 0:
            numbers.remove(num)  # 会导致RuntimeError
except RuntimeError as e:
    print(f"错误: {e}")
# 正确方式:创建副本
print("正确方式(创建副本):")
for num in numbers.copy():
    if num % 2 == 0:
        numbers.remove(num)
print(f"修改后: {numbers}")

这些案例涵盖了Python集合遍历的常见场景,集合是无序的,如果需要有序遍历,建议使用list(sorted(set))collections.OrderedSet

抱歉,评论功能暂时关闭!