Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...