在python中按成对标准列出列表中的元素

时间:2017-10-15 17:27:15

标签: 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

我目前的解决方案似乎有点复杂,我正在寻找大多数pythonic方法:

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列表)。

1 个答案:

答案 0 :(得分:1)

自定义 isolate_group 功能:

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]

测试2:

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

输出:

[[0, 3], 5, 8, [0, 3], 9, 5, [0, 3]]
相关问题