How to separate each element from a list, with a String, in a row

Asked

Viewed 808 times

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 :)

  • 1

    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 several a

  • 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

  • The problem, Isac, is that it is not an eternal second, but a "separator"

  • But the list and the separator must be generated on the same line ? And the list must be generated with list comprehension as indicated ?

  • Yes, Isac. The separator is a variable to be received. Perhaps the use of a lambda function is a possible path

  • 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 using list(zip(l, separador*len(l))), being the separador something like a.

  • 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!

  • You can use itertools with list(itertools.chain.from_iterable(zip(l, separador*len(l)))) and assuming that it previously imports itertools with import itertools. Can always do just need to know what you want exactly.

Show 3 more comments

1 answer

2


Simply change the position of the conditional and use what, in Python, is basically a ternary operator:

lista = [x if x % 2 == 0 else 'a' for x in range(10)]

The value of x shall be [0, 10[, including it in the list if it is even, otherwise the character shall be inserted 'a'. The result will be:

[0, 'a', 2, 'a', 4, 'a', 6, 'a', 8, 'a']

Browser other questions tagged

You are not signed in. Login or sign up in order to post.