2

Given the following list:

a = [[1.0, 1.2, 1.4], [2.0, 2.2], 5.0]

How to I get:

s = '1.0 1.2 1.4 2.0 2.2 5.0

I can't seem to be able to build something out of join(), map() or list comprehensions that doesn't fail due to the non-iterable last member.

John
  • 1,721
  • 3
  • 15
  • 15
  • Related: http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python – halex Mar 26 '13 at 16:38
  • You can also check this answer, which compares several methods of flattening a list: http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python – pcalcao Mar 26 '13 at 16:39

3 Answers3

5

This solution is bit hackish but does the JOB with minimum effort

>>> a = [[1.0, 1.2, 1.4], [2.0, 2.2], 5.0]
>>> str(a)
'[[1.0, 1.2, 1.4], [2.0, 2.2], 5.0]'
>>> str(a).translate(None,'[],')
'1.0 1.2 1.4 2.0 2.2 5.0'
Abhijit
  • 62,056
  • 18
  • 131
  • 204
  • Yeah, I put a similar approach in a comment, but +1 for having the guts to actually give it as an answer. :^) One advantage is that it'll handle arbitrary levels of list nesting automatically. – DSM Mar 26 '13 at 16:50
1
>>> a = [[1.0, 1.2, 1.4], [2.0, 2.2], 5.0]
>>> ' '.join(str(s) for x in a for s in (x if isinstance(x, list) else [x]))
'1.0 1.2 1.4 2.0 2.2 5.0'

This is equivalent in behavior to the following for loop:

tmp = []
for x in a:
    if isinstance(x, list):
        for s in x:
            tmp.append(s)
    else:
        tmp.append(x)
result = ' '.join(tmp)

Note that this assumes only one level of nesting, as in your example. If you need this to work with any arbitrary iterable instead of only lists you can use collections.Iterable, as long as your values are not strings (otherwise it will iterate over the characters in the string).

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
0

I'd go for:

a = [[1.0, 1.2, 1.4], [2.0, 2.2], 5.0]

def try_iter(item):
    try:
        return iter(item)
    except:
        return (item,)

from itertools import chain

print ' '.join(str(s) for s in chain.from_iterable(map(try_iter, a)))
Jon Clements
  • 138,671
  • 33
  • 247
  • 280