Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to multiply string by array

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
like image 837
bdeonovic Avatar asked Apr 14 '26 04:04

bdeonovic


2 Answers

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'
like image 29
Ashwini Chaudhary Avatar answered Apr 16 '26 20:04

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!