I am having nested list of strings as:
A = [[\"A\",\"B\",\"C\"],[\"A\",\"B\"]]
I am trying to join the strings in sublist to get a single l
You can use ''.join with map
here to achieve this as:
>>> A = [["A","B","C"],["A","B"]]
>>> list(map(''.join, A))
['ABC', 'AB']
# In Python 3.x, `map` returns a generator object.
# So explicitly type-casting it to `list`. You don't
# need to type-cast it to `list` in Python 2.x
OR you may use it with list comprehension to get the desired result as:
>>> [''.join(x) for x in A]
['ABC', 'AB']
For getting the results as [['ABC'], ['AB']]
, you need to wrap the resultant string within another list as:
>>> [[''.join(x)] for x in A]
[['ABC'], ['AB']]
## Dirty one using map (only for illustration, please use *list comprehension*)
# >>> list(map(lambda x: [''.join(x)], A))
# [['ABC'], ['AB']]
Issue with your code: In your case ''.join(A) didn't worked because A
is a nested list, but ''.join(A)
tried to join together all the elements present in A
treating them as string. And that's the cause for your error "expected str
instance, list
found". Instead, you need to pass each sublist to your ''.join(..)
call. This can be achieved with map
and list comprehension as illustrated above.