0

I have a list of tuples:

my_lst = [('2.0', '1.01', '0.9'), ('-2.0', '1.12', '0.99')]

I'm looking for a solution to unpack each value so that it prints out a comma separated line of values:

2.0, 1.01, 0.9, -2.0, 1.12, 0.99

The catch is, the lenght of lists vary.

Peter Ritchie
  • 34,528
  • 9
  • 78
  • 98
nutship
  • 4,314
  • 12
  • 46
  • 60

5 Answers5

4

Use join twice:

>>> lis=[('2.0', '1.01', '0.9'), ('-2.0', '1.12', '0.99')]
>>> ", ".join(", ".join(x) for x in lis)
'2.0, 1.01, 0.9, -2.0, 1.12, 0.99'
Ashwini Chaudhary
  • 232,417
  • 55
  • 437
  • 487
4

Use can use itertools chain(..).

>>> from itertools import chain
>>> my_lst = [('2.0', '1.01', '0.9'), ('-2.0', '1.12', '0.99')]
>>> list(chain(*my_lst))
['2.0', '1.01', '0.9', '-2.0', '1.12', '0.99']

And then join them with a ",".

>>> ",".join(list(chain(*my_lst)))
'2.0,1.01,0.9,-2.0,1.12,0.99'
UltraInstinct
  • 41,605
  • 12
  • 77
  • 102
  • 1
    I'd use `chain.from_iterable` instead though it doesn't really matter much in this application. – mgilson May 03 '13 at 15:59
1
for i in my_lst:
    for j in i:
        print j, ", "
Kyle G.
  • 870
  • 2
  • 10
  • 22
1

There's also the standard 2-D iterable flattening mechanism:

>>> ', '.join(x for y in lis for x in y)
'2.0, 1.01, 0.9, -2.0, 1.12, 0.99'

Though I prefer chain.from_iterable

mgilson
  • 283,004
  • 58
  • 591
  • 667
1

You can use itertools.chain, like so:

list(itertools.chain(*lst))

or use some function like:

def chain(*iters):
    for it in iters:
        for elem in it:
            yield elem
pradyunsg
  • 16,339
  • 10
  • 39
  • 91