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.

4

5 回答 5

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'
于 2013-05-03T15:57:02.853 回答
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'
于 2013-05-03T15:58:13.810 回答
1
for i in my_lst:
    for j in i:
        print j, ", "
于 2013-05-03T15:57:12.573 回答
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

于 2013-05-03T16:01:51.677 回答
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
于 2013-05-03T16:12:09.337 回答