Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

python - How to join nested list of strings and get the result as new list of string?

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 list of strings as:

B = [['ABC'],['AB']]

OR,

B = ['ABC','AB']

I tried using ''.join(A) and ''.join(str(v) for v in A) but they didn't work.

This is the error I got:

TypeError: sequence item 0: expected str instance, list found

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...