python循環(huán)打印的生成器使用技巧有哪些

小樊
84
2024-08-10 02:55:36

  1. 使用range()函數(shù)生成指定范圍的數(shù)字序列:
def generate_numbers(n):
    for i in range(n):
        yield i

for num in generate_numbers(5):
    print(num)
  1. 使用列表推導(dǎo)式生成列表:
numbers = [x for x in range(5)]
for num in numbers:
    print(num)
  1. 使用條件表達(dá)式過濾元素:
def generate_numbers(n):
    for i in range(n):
        if i % 2 == 0:
            yield i

for num in generate_numbers(5):
    print(num)
  1. 使用嵌套循環(huán)生成多重循環(huán)序列:
def generate_pairs():
    for i in range(3):
        for j in range(3):
            yield (i, j)

for pair in generate_pairs():
    print(pair)
  1. 使用zip()函數(shù)將多個(gè)生成器合并成一個(gè):
def generate_letters():
    yield from 'abc'

def generate_numbers():
    yield from range(1, 4)

for letter, number in zip(generate_letters(), generate_numbers()):
    print(letter, number)

0