函数接受 iterabls 和 return 一个列表

function takes iterabls and return a list

def group_when(iterable,p):
    x = iter(iterable)
    z = []
    d = []
    try:
        while True:
            y = next(x)
            if p(y) == False:
                z.append(y)
            elif p(y) == True:
                z.append(y)
                d.append(z) 
                z = []
    except StopIteration:
        pass
    return 

group_when 生成器将一个可迭代对象和一个谓词作为参数:它生成列表,每个列表以谓词为真的可迭代对象的值结尾。如果 iterable 以谓词 returns False 的值结束,则生成一个最终列表,其中包含从前一端之后的值到 iterable

产生的最后一个值的所有值

例如:

for i in group_when('combustibles', lambda x : x in 'aeiou'):
    print(i,end='')

打印 5 个列表 ['c'、'o']['m'、'b'、'u']['s'、't', 'i']['b', 'l', 'e']['s'].

我的函数越来越接近正确答案了。当输入为

('combustibles', lambda x : x in 'aeiou') 

我的函数returns

[['c', 'o'], ['m', 'b', 'u'], ['s', 't', 'i'], ['b', 'l', 'e']] 

但正确的输出应该是:

[['c', 'o'], ['m', 'b', 'u'], ['s', 't', 'i'], ['b', 'l', 'e'], ['s']]

因此,我只遗漏了最后一个字母 's'。 谁能告诉我如何解决它?非常感谢

我在下面发布了我遇到的错误,只是为了帮助您理解我的功能:

 26 *Error: Failed [v for v in group_when('combustibles', lambda x : x in 'aeiou')] == [['c', 'o'], ['m', 'b', 'u'], ['s', 't', 'i'], ['b', 'l', 'e'], ['s']]
      evaluated: [['c', 'o'], ['m', 'b', 'u'], ['s', 't', 'i'], ['b', 'l', 'e']] == [['c', 'o'], ['m', 'b', 'u'], ['s', 't', 'i'], ['b', 'l', 'e'], ['s']]
 27 *Error: Failed [v for v in group_when(hide('combustibles'), lambda x : x in 'aeiou')] == [['c', 'o'], ['m', 'b', 'u'], ['s', 't', 'i'], ['b', 'l', 'e'], ['s']]
      evaluated: [['c', 'o'], ['m', 'b', 'u'], ['s', 't', 'i'], ['b', 'l', 'e']] == [['c', 'o'], ['m', 'b', 'u'], ['s', 't', 'i'], ['b', 'l', 'e'], ['s']]

问题是只有在获得谓词时才将 z 添加到 d。因此,如果字符串不以谓词结尾,则最后一次不会添加 z 。所以你需要在最后的某个地方:

if z:
    d.append(z)

只有当它不为空时才添加 z。但是您的代码缺少 yield 或实际的 return 语句,所以我不确定应该在哪里发生。

此外,您不需要直接将其与布尔值进行比较。事实上,您可以执行以下操作:

if p(y):
    z.append(y)
    d.append(z)
    z = []
else:
    z.append(y)

当迭代器中最后一个元素的谓词 returns False 时,您的代码将给出不正确的结果。

z 如果 p(y) 对于 iterable 中的最后一个 y 为 False,则不会附加到 d。你应该处理那个案子。

扩展您的代码并在 except 之后添加 2 行,如下所述:

except StopIteration:
        pass
if len(z) !=0:
    y.append(z)

您可以使用以下代码完成相同的工作:

def group_when(iterable,p):
    z = []
    d = []

    for y in iterable:
        z.append(y)
        if p(y) is True:
            d.append(z)
            z=[]
    if z:
        d.append(z)
    return d

以下是您代码的生成器版本:

def group_when(iterable,p):
    z = []
    for y in iterable:
        z.append(y)
        if p(y) is True:
            yield z
            z=[]
    if z :
        yield z
    return 

所以按照你的原始表格,这就是我解决你问题的方法。

def group_when(iterable,p):
    x = iter(iterable)
    z = []
    d = []
    for y in x:
        z.append(y)
        if p(y):
            d.append(z) 
            z = []
    if z:
        d.append(z) 
    return d   #added the d here, think OP dropped it by accident