Insert element in Python list after every nth element

后端 未结 9 1060
感动是毒
感动是毒 2020-12-01 07:58

Say I have a Python list like this:

letters = [\'a\',\'b\',\'c\',\'d\',\'e\',\'f\',\'g\',\'h\',\'i\',\'j\']

I want to insert an \'x\' after

9条回答
  •  萌比男神i
    2020-12-01 08:39

    Try this

    i = n
    while i < len(letters):
        letters.insert(i, 'x')
        i += (n+1)
    

    where n is after how many elements you want to insert 'x'.

    This works by initializing a variable i and setting it equal to n. You then set up a while loop that runs while i is less then the length of letters. You then insert 'x' at the index i in letters. Then you must add the value of n+1 to i. The reason you must do n+1 instead of just n is because when you insert an element to letters, it expands the length of the list by one.

    Trying this with your example where n is 3 and you want to insert 'x', it would look like this

    letters = ['a','b','c','d','e','f','g','h','i','j']
    i = 3
    while i < len(letters):
        letters.insert(i, 'x')
        i += 4
    
    print letters
    

    which would print out

    ['a', 'b', 'c', 'x', 'd', 'e', 'f', 'x', 'g', 'h', 'i', 'x', 'j']
    

    which is your expected result.

提交回复
热议问题