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.
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]
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)
You can use map:
print map(lambda x: "".join(x[1]),t)
Output:
['EFCC', 'ADDB', 'FDFD', 'EBDB', 'BCCD']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.