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
  • 35,463
  • 9
  • 80
  • 98
nutship
  • 4,624
  • 13
  • 47
  • 64

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
  • 244,495
  • 58
  • 464
  • 504
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
  • 43,308
  • 12
  • 81
  • 104
  • 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
  • 300,191
  • 65
  • 633
  • 696
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
  • 18,287
  • 11
  • 43
  • 96