Reputation: 656
So I have a list of random words like this:
[('Frenchy', 'INTENSE'), ('Frenchy', 'ComputerScienceFTW'), ('Frenchy', 'HelloMrGumby'), ('INTENSE', 'Frenchy'), ('INTENSE', 'ComputerScienceFTW'), ('INTENSE', 'HelloMrGumby'), ('ComputerScienceFTW', 'Frenchy'), ('ComputerScienceFTW', 'INTENSE'), ('ComputerScienceFTW', 'HelloMrGumby'), ('HelloMrGumby', 'Frenchy'), ('HelloMrGumby', 'INTENSE'), ('HelloMrGumby', 'ComputerScienceFTW')]
which is a product of permutation. Now that I have this, I wish to add the item in the tuple together like this:
[('Frenchy', 'INTENSE')] # Was this
'FrenchyINTENSE' # Now this
Is there a way to do it elegantly?
Upvotes: 1
Views: 443
Reputation: 13549
For bigger iterables (and memory efficient usage) you maybe want to use something from itertools module, like starmap function:
import itertools
tuples = [('Frenchy', 'INTENSE'), ('Frenchy', 'ComputerScienceFTW'),]
result = itertools.starmap(lambda a, b: a + b, tuples)
And of course, this is a elegantly way to go too.
Upvotes: 2
Reputation: 1121494
Use a list comprehension to join them; this is easiest with the str.join()
method:
[''.join(t) for t in list_of_tuples]
but you could also use unpacking and straight-up concatenation:
[a + b for a, b in list_of_tuples]
The str.join()
method has the advantage that'll work for sequences of arbitrary length.
Demo:
>>> list_of_tuples = [('Frenchy', 'INTENSE'), ('Frenchy', 'ComputerScienceFTW'), ('Frenchy', 'HelloMrGumby'), ('INTENSE', 'Frenchy'), ('INTENSE', 'ComputerScienceFTW'), ('INTENSE', 'HelloMrGumby'), ('ComputerScienceFTW', 'Frenchy'), ('ComputerScienceFTW', 'INTENSE'), ('ComputerScienceFTW', 'HelloMrGumby'), ('HelloMrGumby', 'Frenchy'), ('HelloMrGumby', 'INTENSE'), ('HelloMrGumby', 'ComputerScienceFTW')]
>>> [''.join(t) for t in list_of_tuples]
['FrenchyINTENSE', 'FrenchyComputerScienceFTW', 'FrenchyHelloMrGumby', 'INTENSEFrenchy', 'INTENSEComputerScienceFTW', 'INTENSEHelloMrGumby', 'ComputerScienceFTWFrenchy', 'ComputerScienceFTWINTENSE', 'ComputerScienceFTWHelloMrGumby', 'HelloMrGumbyFrenchy', 'HelloMrGumbyINTENSE', 'HelloMrGumbyComputerScienceFTW']
>>> [a + b for a, b in list_of_tuples]
['FrenchyINTENSE', 'FrenchyComputerScienceFTW', 'FrenchyHelloMrGumby', 'INTENSEFrenchy', 'INTENSEComputerScienceFTW', 'INTENSEHelloMrGumby', 'ComputerScienceFTWFrenchy', 'ComputerScienceFTWINTENSE', 'ComputerScienceFTWHelloMrGumby', 'HelloMrGumbyFrenchy', 'HelloMrGumbyINTENSE', 'HelloMrGumbyComputerScienceFTW']
Upvotes: 3
Reputation: 78650
Use a list comprehesion. Unpack each tuple of strings and add the strings together.
>>> lst = [('Frenchy', 'INTENSE'), ('Frenchy', 'ComputerScienceFTW')]
>>> [a+b for a,b in lst]
['FrenchyINTENSE', 'FrenchyComputerScienceFTW']
Upvotes: 2