Insert an item between two adjacent list items that satisfy the condition

In python, what a clean way to insert an element between any two elements that satisfy the condition?

Call Type:

insert_between([1,2,3,4,7,8,9,15,16], 0, lambda x,y: x + 1 != y)

must produce:

[1,2,3,4,0,7,8,9,0,15,16]

Is there a better way than repeating and adding a second list?

+3
source share
3 answers
>>> def insert_between(iterable, fill, cond):
...     iterable = iter(iterable)
...     prev = next(iterable)
...     yield prev
...     for cur in iterable:
...             if cond(prev, cur):
...                     yield fill
...             yield cur
...             prev = cur
...
>>>
>>> list(insert_between([1,2,3,4,7,8,9,15,16], 0, lambda x,y: x + 1 != y))
[1, 2, 3, 4, 0, 7, 8, 9, 0, 15, 16]

This is just as effective as you, because you still have to go through one pass on the list, and it only takes one pass. Please note that this is a generator, so you need to send it to the list if you need all the values ​​at once.

+10
source

@katrielalex , , , , . , , .

def insert_between(items, insert_item, compare):
    result = items[:1]
    prev = result[0]
    for item in items[1:]:
        if not compare(prev, item):
            result.append(insert_item)
        result.append(item)
        prev = item
    return result

, , . - while , , , . , , .

def insert_between(items, insert_item, compare):
    i = 1
    while i < len(items):
        if not compare(items[i-1], items[i]):
            items[i:i] = [insert_item]
            i += 1
        i += 1
    return items
+2

You can easily perform the lambda function and reduce

l=[1, 2, 3, 4, 7, 8, 9, 15, 16]
f = lambda l, i: l+[0,i] if l and l[-1]+1!=i else l+[i]
print reduce(f, l, [])
[1, 2, 3, 4, 0, 7, 8, 9, 0, 15, 16]
+1
source

Source: https://habr.com/ru/post/1772543/


All Articles