我在学习itertools模块,并尝试创建一个迭代器,从作为输入提供的iterables返回每个元素。在
Agruments Results
p, q, … p0, q0, … plast, qlast
还有一个附加条款,如果说列表的长度不一样,那么当较短的列表用完时,next(it)
应该从较长的列表中返回元素。在
尝试解决
^{pr2}$哪种解决了我的问题
print(list(it))
输出:
[1, 'a', 2, 'b', 3, 'c', 4, 'd', 5, 6]
有没有更简单或更好的方法?我想找个办法解决这个问题,但没能找到。在
可以使用^{} 展平序列,并使用生成器表达式筛选出
None
值:您可能不想使用
^{pr2}$None
作为sentinel值,而是希望使用专用的sentinel,以便可以在输入列表中使用None
:如果要筛选出falsey values,则还可以使用^{} :
演示:
还有当地的哨兵:
^{} recipes section 还具有:
如果您希望修改代码版本,请从一开始就构建一个生成器(无存储列表
l
):尽管我建议使用上面的内置解决方案。在
相关问题 更多 >
编程相关推荐