1

i'd like to do a recursive read on lists

for example, I have the following:

[x if x % 2 == 0 else [a for a in [9,8,7]] for x in [2,3,4,5]]

And the output is:

[2, [9, 8, 7], 4, [9, 8, 7]]

But I'd like it to be:

[2, 9, 8, 7, 4, 9, 8, 7]

Is it possible?

I've tried

[x if x % 2 == 0 else a for a in [9,8,7] for x in [2,3,4,5]]

And didn't work [2, 9, 4, 9, 2, 8, 4, 8, 2, 7, 4, 7]

Thanks in advance.

jaxkodex
  • 484
  • 2
  • 6
  • 17
  • 1
    `itertools.chain`? It's fairly unclear what the meaning of your comprehension is supposed to be. A regular, more explicit loop might be more readable here. – Wooble Feb 05 '14 at 20:48
  • Note that `[a for a in [9, 8, 7]]` is just a fancy way of writing `[9, 8, 7]`. – RemcoGerlich Feb 05 '14 at 21:04
  • @RemcoGerlich ahahahahaa!! funny, that's my bad! – jaxkodex Feb 05 '14 at 21:10
  • @RemcoGerlich Isn't `[a for a in [9, 8, 7]]` a fancy way of writing `[9, 8, 7][:]`? It is a new list after all. Not that it matters much in this precise context. – Hyperboreus Feb 05 '14 at 23:16
  • Yes, of course, or `list([9, 8, 7])`. But using the literal [9, 8, 7] creates a new list already, of course. If he used a random iterator instead of a literal list it might mean something, but written as it was it just made the expression harder to understand. – RemcoGerlich Feb 06 '14 at 08:24

2 Answers2

2

Or without itertools:

a = [[x] if x % 2 == 0 else [a for a in [9,8,7]] for x in [2,3,4,5]]
a = [i for x in a for i in x]
print (a)
Hyperboreus
  • 31,997
  • 9
  • 47
  • 87
1

itertools takes care of this:

from collections import Iterable
from itertools import chain

t =  [x if x % 2 == 0 else [a for a in [9,8,7]] for x in [2,3,4,5]]
final_list = list(chain.from_iterable(item if isinstance(item,Iterable) and
                    not isinstance(item, basestring) else [item] for item in t))
print(final_list)

Source: flatten list of list through list comprehension

EDIT: The issue with the previous solution was it would only work with arrays with values are the same level (ex. [[1,2], [3,4]]) where as arrays like [5, [1,2], [3,4]] return some chain object because of values at different levels (i.e. 5).

Community
  • 1
  • 1