首页 > 解决方案 > 如何使用 yield 将两个列表中的数字通过索引连接到一个元组中?(Python)

问题描述

我需要制作一个“生成器函数”,它将获取 2 个列表并通过索引将两个列表中的数字连接到一个元组中。例如:

l1 = [3, 2, 1]
l2 = [4, 3, 2]

第一次迭代 (3, 4) 的结果将是 第二次迭代的结果将是 (2, 3) 第三次 (1, 2) 而且,其中一个列表的数字可能比另一个多。在这种情况下,我需要编写条件“如果其中一个列表在迭代时结束,则不再执行迭代。” (使用try, except

我知道,生成器函数使用yield而不是return,但我不知道如何编写这个函数......我这样做了

def generate_something(l1, l2):
    l3 = tuple(tuple(x) for x in zip(l1, l2))
    return l3

输出是

((3, 4), (2, 3), (1, 2))

它可以工作,但这不是 geterator 函数,没有yield,没有第一次、第二次等迭代。我希望你能帮帮我...

标签: pythonlistfunctionconcatenationyield

解决方案


可能对您有帮助:

def generate_something_2(l1, l2):
    # if one of the lists ended while iterating, then no further iterations are performed.
    # For this get minimal len of list
    min_i = len(l1) if len(l1) < len(l2) else len(l2)
    for i in range(0,min_i):
        yield (l1[i], l2[i])

l1 = [3, 2, 1, 1]
l2 = [4, 3, 2]

l3 = tuple(generate_something_2(l1, l2))
# Result: ((3, 4), (2, 3), (1, 2))
print(l3)

推荐阅读