Home > Blockchain >  Inserting elements before a list of indexes
Inserting elements before a list of indexes

Time:06-07

Say we have a python list defined like

>>> letters = ['A', 'B', 'X', 'C', 'D', 'X', 'E', 'F', 'X']

How could you insert an element, say:

>>> c = 'T' 

Such that letters list remains:

 >>> ['A', 'B', 'T', 'X', 'C', 'D', 'T', 'X', 'E', 'F', 'T', 'X']

That is, before each 'X' in the list is inserted 'T'.

My first try was to compute the 'X' indexes like:

>>> xpositions = [pos for pos, e in enumerate(letters) if e == 'X']

And then, execute the following loop:

>>> for xpos in xpositions:
>>>     letter.insert(xpos, c)

But then realized that after the first execution of the loop body, the xpositions are changed. How could be this achieved?

CodePudding user response:

Iterate from end to beginning:

for xpos in xpositions[::-1]:
    letters.insert(xpos, c)

CodePudding user response:

Use list comprehension to insert a list ['T', x] every time X is found. Flatten the resulting mixed list of lists using itertools.chain:

import itertools
letters = ['A', 'B', 'X', 'C', 'D', 'X', 'E', 'F', 'X']
letters = list(itertools.chain(*[['T', x] if x == 'X' else x for x in letters]))
print(letters)

CodePudding user response:

One way is to build a helper function:

def inserter(iterable):
    for it in iterable:
        if it == 'X':
            yield 'T'
        yield it

Then either iterate over it or build a list from it...

result = list(inserter(letters))

CodePudding user response:

letters = ['A', 'B', 'X', 'C', 'D', 'X', 'E', 'F', 'X']
s = "X"
t = 'T'
i = 0
while i < len(letters):
    if letters[i] == s:
        letters.insert(i, t)
        i = i   2
    else:
        i = i   1
print(letters)


CodePudding user response:

The problem you're having is after you append 'T' the X position will change. So what you need to do is update the xpos by making a slight modification to your loop code

letters = ['A', 'B', 'X', 'C', 'D', 'X', 'E', 'F', 'X']

xpositions = [pos for pos, e in enumerate(letters) if e == 'X']

# add the count   xpos to update the xpos after adding 'T' to your list
for count,xpos in enumerate(xpositions):
    letters.insert(xpos count, 'T')

print(letters)
>>> ['A', 'B', 'T', 'X', 'C', 'D', 'T', 'X', 'E', 'F', 'T', 'X']

CodePudding user response:

Not too much pythonic but works

letters = ['A', 'B', 'X', 'C', 'D', 'X', 'E', 'F', 'X']


def add_charater_before_list_element(letters, character, element):
    result = []
    for letter in letters:
        if letter == element:
            result  = [character, letter]
        else:
            result.append(letter)
    return result


if __name__ == '__main__':
    print(add_charater_before_list_element(letters, 'T', 'X'))

Result:

['A', 'B', 'T', 'X', 'C', 'D', 'T', 'X', 'E', 'F', 'T', 'X']
  • Related