用生成函数迭代iterable

2024-05-23 15:47:52 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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组成的类) 谢谢你的帮助


Tags: theinnoneforthatrangefunctioniterable
1条回答
网友
1楼 · 发布于 2024-05-23 15:47:52

尝试在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)

相关问题 更多 >