Python: How to extend or append multiple elements in list comprehension format?

后端 未结 2 1076
不知归路
不知归路 2021-01-19 00:29

I\'d like to get a nice neat list comprehension for this code or something similar!

extra_indices = []
for i in range(len(indices)):
    index = indices[i]
          


        
相关标签:
2条回答
  • 2021-01-19 00:51

    code below should do the equivalant of your code, assuming indices is a list of integer

    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]
    
    0 讨论(0)
  • 2021-01-19 01:01

    You can use two loops in list comp -

    extra_indices = [index+i for index in indices for i in range(3)]
    
    0 讨论(0)
提交回复
热议问题