I have a list of tuples and I want to print flattened form of this list. I don't want to transform the list, just print it without parenthesis and brackets.
input: [ ("a", 1), ("b",2), ("c", 3)]
output: a 1 b 2 c 3
Here's what I do:
l = [ ("a", 1), ("b",2), ("c", 3)]
f = lambda x: " ".join(map(str,x))
print " ".join(f(x) for x in l)
I'm interested in if anybody has a more elegant and possibly a more efficient solution,possibly without doing join, only print. Thanks in advance.
from __future__ import print_function
l = [("a", 1), ("b",2), ("c", 3)]
print(*(i for j in l for i in j))
a 1 b 2 c 3
Or using itertools.chain to flatten:
from itertools import chain
print(*chain(*l))
Using str.join() you can use a nested list comprehension:
>>> print ' '.join([str(i) if isinstance(i,int) else i for tup in A for i in tup])
a 1 b 2 c 3
And without join() still you need to loop over the the items and concatenate them, which I think join() is more pythonic way for this aim.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With