在 Python 中,可以通过多种方式在 for 循环中使用两个变量,以下是几种常见的方法:

方法 1:使用 zip() 函数
适用于同时遍历两个或多个可迭代对象(如列表、元组等),按元素配对。
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
for x, y in zip(list1, list2):
print(f"{x} -> {y}")
输出:
1 -> a
2 -> b
3 -> c
注意:
- 如果两个列表长度不同,
zip()会以较短列表的长度为准。
方法 2:使用 enumerate() 获取索引和值
适用于需要同时获取元素的索引和值。

fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
输出:
Index 0: apple
Index 1: banana
Index 2: cherry
方法 3:手动管理索引(不推荐)
通过 range(len()) 手动控制索引,但代码不够简洁。
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
for i in range(len(list1)):
x = list1[i]
y = list2[i]
print(f"{x} -> {y}")
输出:
1 -> a
2 -> b
3 -> c
缺点:
- 代码冗长,容易出错(如列表长度不一致时)。
方法 4:使用字典的 items()
适用于遍历字典的键和值。
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
for key, value in person.items():
print(f"{key}: {value}")
输出:
name: Alice
age: 25
city: New York
方法 5:使用 itertools.product()(笛卡尔积)
需要两个变量的所有可能组合时使用。
from itertools import product
list1 = [1, 2]
list2 = ['a', 'b']
for x, y in product(list1, list2):
print(f"{x} - {y}")
输出:
1 - a
1 - b
2 - a
2 - b
| 方法 | 适用场景 | 示例 |
|---|---|---|
zip() |
同时遍历多个列表/元组 | for x, y in zip(list1, list2) |
enumerate() |
遍历时获取索引和值 | for i, x in enumerate(list) |
range(len()) |
手动控制索引(不推荐) | for i in range(len(list)) |
dict.items() |
遍历字典的键和值 | for k, v in dict.items() |
itertools.product() |
获取所有组合(笛卡尔积) | for x, y in product(list1, list2) |
选择合适的方法可以让代码更简洁高效!
