Insert element in Python list after every nth element

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

    This is an old topic, but it lacks the easiest, most "pythonic" solution, imo. It is no more than an extension to part 2 of Mark Mikofski's accepted answer that arguably improves readability (and therefore makes it more pythonic).

    >>> letters = ['a','b','c','d','e','f','g','h','i','j']
    >>> [el for y in [[el, 'x'] if idx % 3 == 2 else el for 
         idx, el in enumerate(letters)] for el in y]
    
    ['a', 'b', 'c', 'x', 'd', 'e', 'f', 'x', 'g', 'h', 'i', 'x', 'j']
    

提交回复
热议问题