Insert element in Python list after every nth element

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

    It's worth stating the simple implementation too:

    letters = ['a','b','c','d','e','f','g','h','i','j']
    
    i = 3   #initial step
    while i < len(letters):
        letters.insert(i,'x')
        i = i + 3 + 1  #increment step by one for every loop to account for the added element
    

    It does use basic looping and inserting, but it also looks much simpler and comfortable to read than the one-liner examples, which IMHO makes it more Pythonish as requested in the first place.

提交回复
热议问题