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
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'
>>>
Fastest way to do this will be to use map
with operator.mul
:
>>> from operator import mul
>>> ''.join(map(mul, seq, rep))
'ATCGGGA'
This should do the trick:
"".join([s*r for r, s in zip(rep, seq)])
Output:
"ATCGGGA"