如何加入嵌套的字符串列表并获得结果作为新的字符串列表? [英] How to join nested list of strings and get the result as new list of string?

查看:100
本文介绍了如何加入嵌套的字符串列表并获得结果作为新的字符串列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将嵌套的字符串列表设置为:

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']

我尝试使用''.join(A)''.join(str(v) for v in A),但是它们不起作用.

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

这是我得到的错误:

TypeError:序列项0:预期的str实例,找到了列表

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

推荐答案

您可以使用 ''.join map 在此处实现为:

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']

要以[['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']]


包含您的代码:就您而言的原因.相反,您需要将每个子列表传递给您的''.join(..)调用.如上所示,这可以通过map列表理解来实现.


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.

这篇关于如何加入嵌套的字符串列表并获得结果作为新的字符串列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆