如何将二维数组中的项目连接成一个单独的字符串?

huangapple go评论72阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年7月7日 01:16:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76631169.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定