Reputation: 32680
I have a list of tuples of form
[("very", "ADJ"), ("slow", "ADJ"), ("programmer", "NOUN")]
My desired output is a single string of form:
"very/ADJ slow/ADJ programmer/NOUN"
This being python, I know I can do this in a one-liner using the format()
and join()
methods, but I can't get the syntax quite right. My most recent attempt was:
output_string = " ".join(["{0}/{1}".format(x) for x in list_of_tuples])
which threw an Index Error: tuple index out of range"
Upvotes: 1
Views: 42
Reputation: 103844
You can use map
too:
>>> ' '.join(map(lambda t: '{}/{}'.format(*t), li))
'very/ADJ slow/ADJ programmer/NOUN'
And, that same method without the lambda
:
>>> ' '.join(map('/'.join, li))
'very/ADJ slow/ADJ programmer/NOUN'
Which works even if you have more than two elements in your tuples.
Upvotes: 0
Reputation: 60957
You want format(*x)
so that the x
tuple is expanded into arguments. Otherwise you are trying to call format
with a single argument which is itself a tuple.
That said, if you know that these are all 2-tuples, I'd just go with the simpler:
output_string = " ".join(a + "/" + b for a, b in list_of_tuples)
Also note that there's no need to use a list comprehension to pass into join
-- just use a generator comprehension instead.
Upvotes: 2
Reputation: 49318
words = [("very", "ADJ"), ("slow", "ADJ"), ("programmer", "NOUN")]
' '.join('/'.join((x,y)) for x,y in words)
Upvotes: 1