How to unpack a list of indefinite length
Question:
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.
Answers:
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'
for i in my_lst:
for j in i:
print j, ", "
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'
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
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
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.
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'
for i in my_lst:
for j in i:
print j, ", "
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'
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
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