2

I want to repeat each character in my string by a number I have in an array i.e. if

rep = [1, 0, 1, 1, 3, 0, 0, 1, 0]
seq = 'AATCGGGAA'

I want something like

seq*rep

to output

ATCGGGA
Bach
  • 6,145
  • 7
  • 36
  • 61
bdeonovic
  • 4,130
  • 7
  • 40
  • 70

3 Answers3

6

You can use zip, a list comprehension, and str.join:

>>> rep = [1, 0, 1, 1, 3, 0, 0, 1, 0]
>>> seq = 'AATCGGGAA'
>>>
>>> list(zip(seq, rep)) # zip pairs up the items in the two lists
[('A', 1), ('A', 0), ('T', 1), ('C', 1), ('G', 3), ('G', 0), ('G', 0), ('A', 1), ('A', 0)]
>>>
>>> ''.join([x*y for x,y in zip(seq, rep)])
'ATCGGGA'
>>>
4

Fastest way to do this will be to use map with operator.mul:

>>> from operator import mul
>>> ''.join(map(mul, seq, rep))
'ATCGGGA'
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
2

This should do the trick:

"".join([s*r for r, s in zip(rep, seq)])

Output:

"ATCGGGA"
Jamie Cockburn
  • 7,379
  • 1
  • 24
  • 37