我在编写一个生成器函数时遇到了麻烦,该函数需要一个可迭代的参数和一个整数 x 参数。它输出除最后一个 x 值之外的所有值。它不知道如何计算可迭代输出有多少个值。
我不知道如何使用 while 循环和 iter 来做到这一点。我还需要使用一种理解来创建一个列表来最多存储 x 值。
假设我们打电话:
for i in func_function(“abcdefghijk”,5):
print(i,end =”)
它应该打印abcdef
。
这是我尝试过的:
def func_function(iterable, x):
while True:
l = []
for x in iter(iterable):
if len(x) == x:
yield x
最佳答案
诀窍是将其从前瞻转变为后瞻。
我将通过迭代输入并维护最新 n
元素的窗口来做到这一点:
def except_last_n(iterable, n):
last_n = []
for val in iterable:
last_n.append(val)
if len(last_n) > n:
yield last_n.pop(0)
for val in except_last_n(range(10), 3):
print(val)
将其重写为 while
循环,并将 iter
留给读者作为练习。
def except_last_n(iterable, n):
last_n = [val for val in iterable]
if len(last_n) > n:
yield last_n.pop(0)
关于python - 在使用对 iter 和 while 的调用时,如何将字符串的最后 x 个字符作为 python 生成器删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53077566/