0
The problem is simple, I would like to add an element to a real-time generated list for each given iteration. For example, if the list l is generated through [x for x in range(10) if x%2==0]
, then I want the character 'a' to appear between each element of the list. That is, the list l would be [0,'a',2,'a', 4,'a',6,'a',8]. To solve this problem there are two restrictions: use only the standard library and use list comprehension.
What I’ve tried so far: https://stackoverflow.com/questions/2505529/appending-item-to-lists-within-a-list-comprehension
However, this solution solves the problem using sublists.
Purpose:
My working language is currently Python, but I have invested some time learning Clojure. In this language, purely functional, this task would be solved as follows:
(->> (range 10)(filter even?)(interpose "a") )
I would like to know how to solve this same problem elegantly and pythonica :)
But it has to be all in one call ? Can’t use native functions ? What are the restrictions more specifically speaking ?
zip
solves the problem elegantly, interspersing/merging two iterables in which one can be a list of severala
– Isac
Well remembered! It doesn’t need to be a single call, but it needs to fit in a single line. I mean, it needs to be as succinct as possible
– Kfcaio
The problem, Isac, is that it is not an eternal second, but a "separator"
– Kfcaio
But the list and the separator must be generated on the same line ? And the list must be generated with list comprehension as indicated ?
– Isac
Yes, Isac. The separator is a variable to be received. Perhaps the use of a lambda function is a possible path
– Kfcaio
I’m a little reluctant to answer because I suspect it’s not what you’re looking for because of other reasons you didn’t explain. But assuming you have the list
l
. Get the result you want usinglist(zip(l, separador*len(l)))
, being theseparador
something likea
.– Isac
This way, the result is a list of tuples. I know how to decrease the dimensions in just one list, but I wonder if this is the simplest way to solve the problem. Anyway, it solves. Thank you!
– Kfcaio
You can use itertools with
list(itertools.chain.from_iterable(zip(l, separador*len(l))))
and assuming that it previously imports itertools withimport itertools
. Can always do just need to know what you want exactly.– Isac