Insert element in Python list after every nth element

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

    Although using list.insert() in a for loop seems to be more memory efficient, in order to do it in one-line, you can also append the given value at the end of every equally divided chunks split on every nth index of the list.

    >>> from itertools import chain
    
    >>> n = 2
    >>> ele = 'x'
    >>> lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
    >>> list(chain(*[lst[i:i+n] + [ele] if len(lst[i:i+n]) == n else lst[i:i+n] for i in xrange(0, len(lst), n)]))
    [0, 1, 'x', 2, 3, 'x', 4, 5, 'x', 6, 7, 'x', 8, 9, 'x', 10]
    

提交回复
热议问题