python - 如何使用 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
,没有第一次、第二次等迭代。我希望你能帮帮我...
解决方案
可能对您有帮助:
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)
推荐阅读
- ddl - CREATE TABLE 语句不适用于 CHECK 约束
- javascript - MS Office 加载项、JavaScript 和 async/await
- qt - QGridLayout 中的 MouseEvent
- javascript - 如果文件长度超过 1 GB,如何将文件表单客户端上传到服务器?
- java - 通过示例在 Windows 10 机器上安装 Java 可执行文件
- javascript - 如何显示对象数组的每个元素的长度?
- angular-httpclient - Angular httpClient catchError 不返回错误对象
- javascript - 通过 URL 访问剃须刀页面时,浏览器尝试从无效地址加载 JS 文件
- jinja2 - Jinja2 条件在表达式中不匹配,如何解决?
- android - 我无法在android中使用移动网络