Python: how to extend or add multiple items to a list comprehension format?

I would like to get a good neat list comprehension for this code or something similar!

extra_indices = []
for i in range(len(indices)):
    index = indices[i]
    extra_indices.extend([index, index + 1, index +2])

      

Thank!

Edit * Indices are a list of integers. List of indices of another array.

For example, if the indices are [1, 52, 150], then the target (here, this is the second time I wanted two separate actions on continuously indexed pins in a list comprehension)

Then extra_indices will be [1, 2, 3, 52, 53, 54, 150, 151, 152]

+3


source to share


2 answers


You can use two loops in the comp list -



extra_indices = [index+i for index in indices for i in range(3)]

      

+3


source


the code below should do the equivalent of your code, assuming the indices are a list of integers



from itertools import chain
extra_indices = list(chain(*([x,x+1,x+2] for x in indices)))

>>> indices = range(3)
>>> list(chain(*([x,x+1,x+2] for x in indices)))
>>> [0, 1, 2, 1, 2, 3, 2, 3, 4]

      

+3


source







All Articles