Home > Net >  how to convert a number to range of tokens
how to convert a number to range of tokens

Time:10-18

Bit hard to explain but I want to convert a range of numbers to a range of ones and zeros, but not a binary conversion.

As an example : I have a list with 3 numbers, the first number needs to be converted to zeros, the second to ones, the third to zeros again.

so (3,5,2) would become 0001111100 (3 times zero, 5 times 1, 2 times 0)

While this is fairly easy to do for one single list using range I need to be able to do this for hundreds of thousands rows (using pyspark) and my first tryout (basic sample below) is a bit slow, so I was wondering if there were better / more efficient ways to do this

lst = (3,5,2)

out = ''

for i in range(lst[0]):
    out = out   '0'
for i in range(lst[1]):
    out = out   '1'
for i in range(lst[2]):
    out = out   '0'

print(out)
# result : 0001111100

CodePudding user response:

Don't do it with a loop, for goodness sakes. Python lets you repeat a string using the * operator.

out = ''
which = 0
for n in [3,5,2]:
    out  = '01'[which] * n
    which = 1 - which

CodePudding user response:

You could do this with a comprehension, noting that when the index of lst is even, the output is 0 and vice versa:

lst = [3,5,2]
out = ''.join(str(i % 2) * n for i, n in enumerate(lst))

Output:

0001111100
  • Related