useR
useR

Reputation: 3082

Python multiplication of two list

I am new to Python and noticed that the following.

>>> 'D'*1
'D'

Therefore i wonder whether we can do multiplication and join the string (for choice, element can be 0 or 1 only)

>>> print(choice)
[1, 1, 1, 1]
>>> print(A)
['D', 'e', '0', '}']

My desired output would be 'De0}'

Upvotes: 2

Views: 177

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1124968

You can explicity zip the lists, mulitply and then join the result:

''.join([c * i for c, i in zip(A, choice)])

The zip() function pairs up the characters from A with the integers from choice, the list comprehension then multiplies the character with the integer, and the str.join() call combines the result of that into one string.

If choice is used just used to select elements, you are better of using itertools.compress() here:

from itertools import compress

''.join(compress(A, choice))

compress() does exactly what you were intending to do: pick elements from the first iterable based on wether or not the corresponding value in the second iterable is true or false.

Demo:

>>> choice = [1, 1, 1, 1]
>>> A = ['D', 'e', '0', '}']
>>> ''.join([c * i for c, i in zip(A, choice)])
'De0}'
>>> choice = [0, 1, 0, 1]
>>> ''.join([c * i for c, i in zip(A, choice)])
'e}'
>>> from itertools import compress
>>> ''.join(compress(A, choice))
'e}'

Using itertools.compress() is the far faster option here:

>>> import timeit
>>> import random
>>> A = [chr(random.randrange(33, 127)) for _ in range(1000)]
>>> choice = [random.randrange(2) for _ in range(1000)]
>>> def with_mult(A, choice):
...     return ''.join([c * i for c, i in zip(A, choice)])
... 
>>> def with_compress(A, choice):
...     return ''.join(compress(A, choice))
... 
>>> timeit.timeit('f(A, choice)', 'from __main__ import A, choice, with_mult as f', number=10000)
1.0436905510141514
>>> timeit.timeit('f(A, choice)', 'from __main__ import A, choice, with_compress as f', number=10000)
0.2727453340048669

That's a 4x speed increase.

Upvotes: 7

Ffisegydd
Ffisegydd

Reputation: 53718

You can use a list comprehension with str.join and zip. See below for an example:

choice = [1, 1, 1, 0]
A = ['D', 'e', '0', '}']

out = ''.join([n*c for n, c in zip(choice, A)])

print(out)
# De0

As the 4th element of choice is 0 the 4th element of A ('}') is not printed.

Upvotes: 5

Related Questions