Specific iterator in one line

  • Thread starter Filip GruszczyÅ„ski
  • Start date
F

Filip Gruszczyński

This is purely sport question. I don't really intend to use the answer
in my code, but I am wondering, if such a feat could be done.

I have a following problem: I have a list based upon which I would
like to construct a different one. I could simply use list
comprehensions, but there is an additional trick: for some elements on
this list, I would like to return two objects. For example I have a
list of 0s and 1s and for 0 I would like to add 1 'a' and for 1 I
would like to add 2 'b', like this:

[1, 0, 0, 1] -> ['b', 'b', 'a', 'a', 'b', 'b']

The easy way is to return a tuple ('b', 'b') for 1s and then flatten
them. But this doesn't seem very right - I'd prefer to create a nice
iterable right away. Is it possible to achieve this? Curiosly, the
other way round is pretty simple to achieve, because you can filter
objects using if in list comprehension.
 
B

Bearophile

Filip Gruszczyñski:
[1, 0, 0, 1] -> ['b', 'b', 'a', 'a', 'b', 'b']

I like this version (43 golf holes), it's readable enough:

[c for d in[1,0,0,1]for c in("a","bb")[d]]

Bye,
bearophile
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,201
Messages
2,571,049
Members
47,655
Latest member
eizareri

Latest Threads

Top