python 中常见的遍历迭代场景用法
在 Python 中,遍历是一个非常常见且重要的操作,通常用于迭代列表、字典、元组等数据结构。以下是一些常见的遍历用法,涵盖了不同的数据类型和用法。
1. 遍历列表(List)
列表是 Python 中最常见的可迭代对象之一。可以使用 for
循环直接遍历列表中的元素。
示例:
my_list = [1, 2, 3, 4, 5]
# 使用 for 循环遍历列表元素
for item in my_list:
print(item)
输出:
1
2
3
4
5
2. 遍历元组(Tuple)
元组与列表类似,也是一个可迭代对象。遍历元组的方式与遍历列表相同。
示例:
my_tuple = ('apple', 'banana', 'cherry')
for item in my_tuple:
print(item)
输出:
apple
banana
cherry
3. 遍历字典(Dictionary)
字典是 Python 中常用的键值对数据结构。可以通过不同的方式遍历字典,常见的有按键、按值、按键值对遍历。
按键遍历字典:
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key in my_dict:
print(key) # 也可以写作: for key in my_dict.keys()
输出:
a
b
c
按值遍历字典:
for value in my_dict.values():
print(value)
输出:
1
2
3
按键值对遍历字典:
for key, value in my_dict.items():
print(key, value)
输出:
a 1
b 2
c 3
4. 使用 enumerate()
同时遍历索引和值
enumerate()
是一个非常有用的内置函数,它可以让你在遍历一个可迭代对象时,同时获得元素的索引和值。
示例:
my_list = ['apple', 'banana', 'cherry']
for index, value in enumerate(my_list):
print(f"Index: {index}, Value: {value}")
输出:
Index: 0, Value: apple
Index: 1, Value: banana
Index: 2, Value: cherry
5. 遍历字符串(String)
字符串是一个字符序列,也是可迭代对象,可以用 for
循环遍历其中的每个字符。
示例:
my_string = "hello"
for char in my_string:
print(char)
输出:
h
e
l
l
o
6. 遍历集合(Set)
集合是一个无序的可迭代对象,可以直接使用 for
循环遍历。
示例:
my_set = {1, 2, 3, 4, 5}
for item in my_set:
print(item)
输出:
1
2
3
4
5
(注意:集合是无序的,因此输出顺序可能不同。)
7. 列表推导式(List Comprehensions)
列表推导式是一种简洁的遍历方式,用于根据某个可迭代对象创建一个新的列表。它允许你在一行代码中完成遍历和过滤操作。
示例:
my_list = [1, 2, 3, 4, 5]
# 创建一个新列表,将原列表的元素平方
squared_list = [x**2 for x in my_list]
print(squared_list)
输出:
[1, 4, 9, 16, 25]
好的,继续输出:
8. 字典推导式(Dictionary Comprehensions)(续)
字典推导式允许你通过遍历现有字典或其他可迭代对象来生成新的字典。它与列表推导式类似,但生成的是键值对的字典。
示例:
my_dict = {'a': 1, 'b': 2, 'c': 3}
# 创建一个新字典,将值乘以2
new_dict = {key: value * 2 for key, value in my_dict.items()}
print(new_dict)
输出:
{'a': 2, 'b': 4, 'c': 6}
9. 使用 zip()
函数同时遍历多个可迭代对象
zip()
函数可以将多个可迭代对象(如列表、元组等)打包成元组,并返回一个迭代器。常用于同时遍历多个列表。
示例:
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
# 同时遍历 names 和 ages
for name, age in zip(names, ages):
print(f"{name} is {age} years old.")
输出:
Alice is 25 years old.
Bob is 30 years old.
Charlie is 35 years old.
如果两个可迭代对象的长度不同,zip()
会以最短的一个为准。
10. 遍历生成器(Generator)
生成器是惰性计算的序列,使用 yield
来生成序列中的一个个元素。在遍历生成器时,只有在需要时才会计算下一个元素。
示例:
def count_up_to(limit):
count = 1
while count <= limit:
yield count
count += 1
# 创建生成器
gen = count_up_to(5)
# 遍历生成器
for num in gen:
print(num)
输出:
1
2
3
4
5
生成器的好处是它不会一次性将所有数据加载到内存中,而是按需生成数据,节省内存。
11. 使用 itertools
库进行更复杂的遍历
itertools
是 Python 的标准库,提供了一些非常有用的迭代器工具,可以帮助进行更复杂的遍历操作,比如:组合、排列、重复等。
11.1 itertools.count()
:生成无限序列
import itertools
# 使用 count() 生成一个无限序列,从 0 开始
for num in itertools.count(start=0, step=2): # 步长为 2
if num > 10:
break
print(num)
输出:
0
2
4
6
8
10
11.2 itertools.cycle()
:循环遍历
itertools.cycle()
可以让你循环遍历一个序列。它会无限重复地遍历序列,直到你手动停止。
import itertools
# 使用 cycle() 循环遍历一个序列
for item in itertools.cycle(['a', 'b', 'c']):
if item == 'c':
break
print(item)
输出:
a
b
11.3 itertools.combinations()
:获取所有组合
itertools.combinations()
用于从一个可迭代对象中获取指定长度的所有组合。
import itertools
# 获取所有长度为 2 的组合
items = ['a', 'b', 'c']
combs = itertools.combinations(items, 2)
for comb in combs:
print(comb)
输出:
('a', 'b')
('a', 'c')
('b', 'c')
11.4 itertools.permutations()
:获取所有排列
itertools.permutations()
用于获取所有指定长度的排列。
import itertools
# 获取所有长度为 2 的排列
items = ['a', 'b', 'c']
perms = itertools.permutations(items, 2)
for perm in perms:
print(perm)
输出:
('a', 'b')
('a', 'c')
('b', 'a')
('b', 'c')
('c', 'a')
('c', 'b')
好的,继续输出:
12. 嵌套遍历(Nested Iteration)
当你处理多维数据结构(如列表的列表、字典的字典等)时,通常需要使用嵌套的 for
循环来遍历内部的数据。这里是一些常见的嵌套遍历例子。
12.1 遍历列表的列表(二维列表)
假设我们有一个二维列表(列表的列表),你可以使用嵌套的 for
循环来遍历每一行和每个元素。
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# 遍历二维列表
for row in matrix:
for item in row:
print(item)
输出:
1
2
3
4
5
6
7
8
9
12.2 遍历字典的字典
如果你有一个字典,其中的值是另一个字典,你可以通过嵌套循环遍历这些字典。
nested_dict = {
'first': {'name': 'Alice', 'age': 30},
'second': {'name': 'Bob', 'age': 25},
'third': {'name': 'Charlie', 'age': 35}
}
# 遍历字典的字典
for key, inner_dict in nested_dict.items():
print(f"Key: {key}")
for sub_key, value in inner_dict.items():
print(f" {sub_key}: {value}")
输出:
Key: first
name: Alice
age: 30
Key: second
name: Bob
age: 25
Key: third
name: Charlie
age: 35
13. 反向遍历
有时你可能需要反向遍历列表、元组等序列。可以使用 reversed()
函数或切片来实现反向遍历。
13.1 使用 reversed()
反向遍历
reversed()
返回一个反向迭代器,适用于任何可迭代对象。
my_list = [1, 2, 3, 4, 5]
# 使用 reversed() 反向遍历
for item in reversed(my_list):
print(item)
输出:
5
4
3
2
1
13.2 使用切片反向遍历
切片是另一种反向遍历序列的简便方式。
my_list = [1, 2, 3, 4, 5]
# 使用切片反向遍历
for item in my_list[::-1]:
print(item)
输出:
5
4
3
2
1
14. 带条件的遍历(过滤数据)
有时你在遍历时只对满足某个条件的数据感兴趣,可以在遍历时加入条件判断。
14.1 遍历列表并过滤满足条件的元素
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 遍历并只打印偶数
for num in numbers:
if num % 2 == 0:
print(num)
输出:
2
4
6
8
10
14.2 列表推导式结合条件过滤
列表推导式结合条件判断能够更加简洁地完成遍历和过滤。
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 使用列表推导式过滤偶数
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers)
输出:
[2, 4, 6, 8, 10]
以上是在 Python 中,处理数据常用的遍历操作。你可以使用 for
循环遍历列表、元组、字典、集合、字符串等多种可迭代对象。常见的遍历方法包括基本的 for
循环、enumerate()
获取索引、zip()
同时遍历多个可迭代对象、列表推导式和字典推导式等。对于更复杂的结构,如嵌套列表或字典,可以使用嵌套循环进行遍历。此外,生成器和 itertools
库提供了高效的遍历方式,特别适用于大规模数据的处理。
作者:风_流沙