需要实现Python itertools函数的“链"功能.在课堂上 [英] Need to implement the Python itertools function "chain" in a class
本文介绍了需要实现Python itertools函数的“链"功能.在课堂上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在python的itertools中模拟链"功能.
I am trying to emulate the "chain" function in itertools in python.
我想出了以下生成器.
# Chain make an iterator that returns elements from the first iterable
# until it is exhausted, then proceeds to the next iterable, until all
# of the iterables are exhausted.
def chain_for(*a) :
if a :
for i in a :
for j in i :
yield j
else :
pass
如何在类中模拟相同的函数? 由于该函数的输入是任意数量的列表,所以我不确定是否可以在类中使用包装/拆包,如果可以,我不确定如何在' init '方法中拆包
How can I emulate the same function in a class? Since the input to the function is an arbitrary number of lists, I am not sure if packing/unpacking can be used in classes, and if so I am not sure how to unpack in the 'init' method.
class chain_for :
def __init__(self, ...) :
....
def __iter__(self) :
self
def __next__(self) :
.....
谢谢.
推荐答案
def chain_for(*a):
和def __init__(self, *a):
之间没有(太多)区别.
因此,实现此目标的一种非常粗略的方法可以是:
There is not (much) difference between def chain_for(*a):
and def __init__(self, *a):
.
Hence, a very crude way to implement this can be:
class chain_for:
def __init__(self, *lists):
self.lists = iter(lists)
self.c = iter(next(self.lists))
def __iter__(self):
while True:
try:
yield next(self.c)
except StopIteration:
try:
self.c = iter(next(self.lists))
except StopIteration:
break
yield next(self.c)
chain = chain_for([1, 2], [3], [4, 5, 6])
print(list(chain))
输出:
[1, 2, 3, 4, 5, 6]
这篇关于需要实现Python itertools函数的“链"功能.在课堂上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文