英文:
How can I concatenate items in a 2 dimensional array to a single string?
问题
我有一个2D数组,像这样:
T = [["w", "b"],["y","b","w"],["f","z"]]
对于一维数组,我知道我可以像这样做:T2 = ' '.join(T)
,但在二维数组上不起作用,我尝试遍历数组,但没有成功。
我想要连接T中每个单独数组内部的项目。我该如何做?
英文:
Let's say I have a 2d array like so
T = [["w", 'b'],["y",'b','w'],["f","z"]]
For a one dimensional array I know I would do something like T2 = ' '.join(T)
but it doesn't work the same way on a 2d array, I tried to iterate through the array but to no avail.
I want to concatenate the items inside of each separate array inside T. How can I do this?
答案1
得分: 2
如果您想要连接每个内部列表中的字符串,可以执行以下操作:
T2 = [' '.join(a) for a in T]
或者
T2 = list(map(' '.join, T))
这两种方法都会生成一个由内部列表连接字符串组成的字符串列表。
英文:
If you're trying to concatenate the strings in each individual inner list you can do something like
T2 = [' '.join(a) for a in T]
or
T2 = list(map(' '.join, T))
Either of these will spit out a list of strings consisting of the concatenated strings of the inner list.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论