Andy Shearer
Andy Shearer

Reputation: 177

Python merge second part of tuple list into list of strings

I have only recently started learning Python, and I have looked at similar questions and cannot seem to find an example that helps - I have this list of tuples currently:

 [('E', ['E', 'F', 'C', 'C']), ('F', ['A', 'D', 'D', 'B']), ('I', ['F', 'D', 'F', 'D']), ('R', ['E', 'B', 'D', 'B']), ('S', ['B', 'C', 'C', 'D'])]

and I want to split them up into a list of strings, so that they look like this:

['EFCC', 'ADDB', 'FDFD', 'EBDB', 'BCCD']

I have tried to use the '.join' function for this, as shown below:

stringList = "".join([str(x[1]) for x in sortedList])

but this provides me with a list in the form:

['B', 'D', 'E', 'C']['B', 'C', 'B', 'D']['E', 'C', 'D', 'C']['B', 'C', 'D', 'C']['C', 'E', 'F', 'A']

I think I am using the join method wrong, but after changing a few bits about in it, I can't figure out how to get the format I want.

Upvotes: 3

Views: 1462

Answers (3)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

Your problem is str(x[1]).

x[1] is a list, and you convert it to a string:

>>> x = ('E', ['E', 'F', 'C', 'C'])
>>> x[1]
['E', 'F', 'C', 'C']

>>> str(x[1])
"['E', 'F', 'C', 'C']"

What you want is to join the elements of the list:

>>> ''.join(x[1])
'EFCC'

So your code would become:

[''.join(x[1]) for x in sortedList]

Upvotes: 6

Ahasanul Haque
Ahasanul Haque

Reputation: 11134

You can use map:

print map(lambda x: "".join(x[1]),t)

Output:

['EFCC', 'ADDB', 'FDFD', 'EBDB', 'BCCD']

Upvotes: 1

Paul Rooney
Paul Rooney

Reputation: 21609

Use a list comprehension and join the strings, like so.

t = [('E', ['E', 'F', 'C', 'C']), ('F', ['A', 'D', 'D', 'B']), ('I', ['F', 'D', 'F', 'D']), ('R', ['E', 'B', 'D', 'B']), ('S', ['B', 'C', 'C', 'D'])]

x = [''.join(b) for a, b in t]
print(x)

Upvotes: 2

Related Questions