Python: How to make each term of an array repeat, with the same terms grouped together

  • A+
Category:Languages

My array is [A,B,C] and I want to multiply it so I can make the array [A,A,A,B,B,B,C,C,C]

 


you can chain the results of itertools.repeat:

import itertools list(itertools.chain.from_iterable(itertools.repeat(x,3) for x in ["A","B","C"])) 

result:

['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'] 

this solution minimizes the loops & the temporary lists (none is created)

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: