使用生成器函数迭代可迭代对象

iterating over an iterable using generator function

我正面临这个问题,我希望你们中的一些人能帮忙:

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)

return 值为

(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 组成的 class) 谢谢您的帮助!

尝试在 for 循环中初始化元组

def bunch_together(iterable,n):

    for k in range(0,len(iterable),n):
        tup = tuple()
        for i in range(k,k+n):
            tup += (iterable[i] if i<len(iterable) else None,) # condition to check overflow
        yield tup

for x in bunch_together(range(10),3): 
    print(x)

输出

(0, 1, 2)
(3, 4, 5)
(6, 7, 8)
(9, None, None)