Python for循环技巧

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ =

from itertools import zip_longest
from itertools import chain

# 并行遍历多个序列
names = ['Alice', 'Bob', 'Charlie']
scores = [85, 92, 78, 70]
for name, score in zip(names, scores):
    print(f"{name}: {score}分")

# 使用zip_longest处理不等长序列
for name, score in zip_longest(names, scores):
    print(f"{name}: {score}分")

# 遍历列表同时获取索引
fruits = ['apple', 'banana', 'cherry']
for idx, fruit in enumerate(fruits, start=1):  # start参数自定义起始索引
    print(f"{idx}. {fruit}")

# 嵌套列表展开(itertools.chain)
matrix = [[1, 2], [3, 4], [5, 6]]
for num in chain.from_iterable(matrix):  # 比双重循环更高效
    print(num)  # 输出: 1, 2, 3, 4, 5, 6

# 逆序遍历
for i in reversed(range(5)):
    print(i)  # 输出: 4, 3, 2, 1, 0

你可能感兴趣的:(python,前端,linux,数据库,javascript)