Insert element in Python list after every nth element

后端 未结 9 1069
感动是毒
感动是毒 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:25

    A pretty straightforward method:

    >>> letters = ['a','b','c','d','e','f','g','h','i','j']
    >>> new_list = []
    >>> n = 3
    >>> for start_index in range(0, len(letters), n):
    ...     new_list.extend(letters[start_index:start_index+n])
    ...     new_list.append('x')
    ... 
    >>> new_list.pop()
    'x'
    >>> new_list
    ['a', 'b', 'c', 'x', 'd', 'e', 'f', 'x', 'g', 'h', 'i', 'x', 'j']
    

    You can also use the grouper recipe from the itertools documentation for the chunking.

提交回复
热议问题