Insert element in Python list after every nth element

后端 未结 9 1054
感动是毒
感动是毒 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条回答
  • 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.

    0 讨论(0)
  • 2020-12-01 08:39

    While Mark Mikofski's answer works, there is a faster solution by assigning slices:

    import string
    
    # The longer the list the more speed up for list3
    # letters = ['a','b','c','d','e','f','g','h','i','j']
    letters = list(string.ascii_letters)
    print("org:", letters)
    
    # Use enumerate to get index, add 'x' every 3rd letter, eg: mod(n, 3) == 2, then concatenate into string and list() it.
    list1 = list(''.join(l + 'x' * (n % 3 == 2) for n, l in enumerate(letters)))
    print("list1:", list1)
    %timeit list(''.join(l + 'x' * (n % 3 == 2) for n, l in enumerate(letters)))
    
    # But as @sancho.s points out this doesn't work if any of the elements have more than one letter.
    # Use nested comprehensions to flatten a list of lists(a), sliced in groups of 3 with 'x' added if less than 3 from end of list.
    list2 = [x for y in (letters[i:i+3] + ['x'] * (i < len(letters) - 2) for i in range(0, len(letters), 3)) for x in y]
    print("list2:", list2)
    %timeit [x for y in (letters[i:i+3] + ['x'] * (i < len(letters) - 2) for i in range(0, len(letters), 3)) for x in y]
    
    # Use list slice assignments
    len_letters = len(letters)
    len_plus_x = ll // 3
    list3 = [None for _ in range(len_letters + len_plus_x)]
    list3[::4] = letters[::3]
    list3[2::4] = letters[2::3]
    list3[1::4] = letters[1::3]
    list3[3::4] = ['x' for _ in range(len_plus_x)]
    print("list3:", list3)
    %timeit ll = len(letters); lp = ll//3; new_letters = [None for _ in range(ll + lp)]; new_letters[::4] = letters[::3]; new_letters[2::4] = letters[2::3]; new_letters[1::4] = letters[1::3]; new_letters[3::4] = ['x' for _ in range(lp)]
    

    produces (using jupyter notebook)

    org: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    list1: ['a', 'b', 'c', 'x', 'd', 'e', 'f', 'x', 'g', 'h', 'i', 'x', 'j', 'k', 'l', 'x', 'm', 'n', 'o', 'x', 'p', 'q', 'r', 'x', 's', 't', 'u', 'x', 'v', 'w', 'x', 'x', 'y', 'z', 'A', 'x', 'B', 'C', 'D', 'x', 'E', 'F', 'G', 'x', 'H', 'I', 'J', 'x', 'K', 'L', 'M', 'x', 'N', 'O', 'P', 'x', 'Q', 'R', 'S', 'x', 'T', 'U', 'V', 'x', 'W', 'X', 'Y', 'x', 'Z']
    13 µs ± 1.09 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    list2: ['a', 'b', 'c', 'x', 'd', 'e', 'f', 'x', 'g', 'h', 'i', 'x', 'j', 'k', 'l', 'x', 'm', 'n', 'o', 'x', 'p', 'q', 'r', 'x', 's', 't', 'u', 'x', 'v', 'w', 'x', 'x', 'y', 'z', 'A', 'x', 'B', 'C', 'D', 'x', 'E', 'F', 'G', 'x', 'H', 'I', 'J', 'x', 'K', 'L', 'M', 'x', 'N', 'O', 'P', 'x', 'Q', 'R', 'S', 'x', 'T', 'U', 'V', 'x', 'W', 'X', 'Y', 'x', 'Z']
    13.7 µs ± 336 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    list3: ['a', 'b', 'c', 'x', 'd', 'e', 'f', 'x', 'g', 'h', 'i', 'x', 'j', 'k', 'l', 'x', 'm', 'n', 'o', 'x', 'p', 'q', 'r', 'x', 's', 't', 'u', 'x', 'v', 'w', 'x', 'x', 'y', 'z', 'A', 'x', 'B', 'C', 'D', 'x', 'E', 'F', 'G', 'x', 'H', 'I', 'J', 'x', 'K', 'L', 'M', 'x', 'N', 'O', 'P', 'x', 'Q', 'R', 'S', 'x', 'T', 'U', 'V', 'x', 'W', 'X', 'Y', 'x', 'Z']
    4.86 µs ± 35.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    
    0 讨论(0)
  • 2020-12-01 08:40
    l = ['a','b','c','d','e','f','g','h','i','j']
    [ l.insert(n+(n+1)*i, 'x') for i in range(len(l)/n) ]
    print l
    
    0 讨论(0)
提交回复
热议问题