我面临这个问题,我希望你们中的一些人能帮上忙:
Write a function that accepts an iterable and a positive number n. The function returns a new iterator that gives values from the original in tuples of length n. Pad missing values with 'None' if needed for the very last tuple.
例如:
for x in bunch_together(range(10),3): print(x)
返回值为
(0, 1, 2)
(3, 4, 5)
(6, 7, 8)
(9, None, None)
到目前为止,我得出的结论是:
def bunch_together(iterable,n):
tup = tuple()
for item in iterable:
for i in range(n):
tup += (i,)
yield tup
但这显然不起作用,因为我根本没有考虑范围(到目前为止的输出如下所示:
(0, 1, 2)
(0, 1, 2, 0, 1, 2)
(0, 1, 2, 0, 1, 2, 0, 1, 2)
...#(goes on)
我可以创建一个生成器或者构建一个迭代器(比如构建一个由init iter和next组成的类) 谢谢你的帮助
尝试在
for
循环内初始化元组输出
相关问题 更多 >
编程相关推荐