I have a list that looks something like this:
a = [('A', 'V', 'C'), ('A', 'D', 'D')]
And I want to create another list that transforms a
into:
['AVC', 'ADD']
How would I go on to do this?
There is no need in square brackets inside join() it could be: ' '. join(str(c) for c in lst) or ' '. join(map(str, lst)) .
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
In this example, we will use list comprehension to Iterate the list first, and then we are iterating the sub-list using for loop. After that, we are appending the element in our new list “flatList” using a List Comprehension which gives us a flat list of 1 dimensional.
To create a list of strings, first use square brackets [ and ] to create a list. Then place the list items inside the brackets separated by commas. Remember that strings must be surrounded by quotes. Also remember to use = to store the list in a variable.
Use str.join()
in a list comprehension (works in both Python 2.x and 3.x):
>>> a = [('A', 'V', 'C'), ('A', 'D', 'D')]
>>> [''.join(x) for x in a]
['AVC', 'ADD']
You could map str.join
to each tuple
in a
:
Python 2:
>>> map(''.join, a)
['AVC', 'ADD']
In Python 3, map
is an iterable object so you'd need to materialise it as a list
:
>>> list(map(''.join, a))
['AVC', 'ADD']
Using reduce
is another option:
>>> a = [('A','V','C'), ('A','D','D')]
In Python 2:
>>> [reduce(lambda x, y: x + y , i) for i in a]
['AVC', 'ADD']
In Python 3 (Thanks for eugene's suggestion):
>>> from functools import reduce
>>> [reduce(lambda x, y: x + y , i) for i in a]
['AVC', 'ADD']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With