python中按成对标准对列表中的元素进行分组

python中按成对标准对列表中的元素进行分组,python,list,iterator,Python,List,Iterator,我正在实现一个将对象融合在一起的局部优化。以最简单的形式,给出一个列表: [0,3,5,8,1,2,9,0,3,5] 我想分为: [[0,3,5,8,1,2,9,0,3,5] 基于提供的标准: def is_group(a, b): return a == 0 and b == 3 我目前的解决方案似乎有点复杂,我正在寻找最具python风格的方法: def pairwise(iterable): for (a, b) in zip(iterable, iterable[1:]

我正在实现一个将对象融合在一起的局部优化。以最简单的形式,给出一个列表:

[0,3,5,8,1,2,9,0,3,5]

我想分为:

[[0,3,5,8,1,2,9,0,3,5]

基于提供的标准:

def is_group(a, b):
    return a == 0 and b == 3
我目前的解决方案似乎有点复杂,我正在寻找最具python风格的方法:

def pairwise(iterable):
    for (a, b) in zip(iterable, iterable[1:]):
        yield (a, b)
    yield (iterable[-1], None)  # handle edge case

def fuse(ops):
    ops_new = []
    skip_next = False
    for (a, b) in pairwise(ops):
        if is_group(a, b):
            ops_new.append([a, b])
            skip_next = True
        elif skip_next:
            skip_next = False
        elif:
            ops_new.append(a)
我已经研究了
groupby
,这是最接近的,但不太确定如何使其工作,因为这里的标准取决于成对参数


编辑:问这个问题的另一种方式是,我基本上是在尝试进行模式搜索,并用列表替换(例如,列表的
regex

自定义
隔离组
功能:

def isolate_group(pair, l):
    result = []
    idx_skip = -1

    for i in range(len(l)):
        if i == idx_skip:
            continue
        if l[i:i+2] == pair:
            result.append(l[i:i+2])
            idx_skip = i+1
        else:
            result.append(l[i])

    return result
测试1:

print(isolate_group([0,3], [0, 3, 5, 8, 1, 2, 9, 0, 3, 5]))
输出:

[[0, 3], 5, 8, 1, 2, 9, [0, 3], 5]
[[0, 3], 5, 8, [0, 3], 9, 5, [0, 3]]

测试2:

print(isolate_group([0,3], [0, 3, 5, 8, 0, 3, 9, 5, 0, 3]))
输出:

[[0, 3], 5, 8, 1, 2, 9, [0, 3], 5]
[[0, 3], 5, 8, [0, 3], 9, 5, [0, 3]]

您正在成对处理的边缘情况是什么?那么,你为什么要考虑最后一个元素反对<代码>没有< /代码>?谢谢你的问题。如果我不包括该处理,那么pairwise只返回
(0,3)、(3,5)、(5,8)、(3,5)
。我的fuse操作从不追加
b
,因此我的结果总是缺少最后一个元素。啊哈,这是有道理的。那么,在这种情况下,我唯一要更改的是
从itertools导入zip_longest,islice
然后简单地
zip_longest(x,islice(x,1,None))
而不是您的
成对