1

I have a list of tuples I would like to print in CSV format without quotes or brackets.

[(('a','b','c'), 'd'), ... ,(('e','f','g'), 'h')]

Desired output:

a,b,c,d,e,f,g,h

I can get rid of some of the punctuation using chain, .join() or the *-operator, but my knowledge is not sophisticated enough to get rid of all of it for my particular use case.

Thank you.

xoihiox
  • 101
  • 6

1 Answers1

1

So, in your case there is a pattern which makes this relatively easy:

>>> x = [(('a','b','c'), 'd') ,(('e','f','g'), 'h')]
>>> [c for a,b in x for c in (*a, b)]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

Or, an itertools.chain solution:

>>> list(chain.from_iterable((*a, b) for a,b in x))
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
>>>

And, in case you are on an old version of Python, and can't use (*a, b) you will need something like:

[c for a,b in x for c in a+(b,)]
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172