明智的元素串联多个列表(字符串列表的列表) [英] Element wise concatenate multiple lists (list of list of strings)

查看:92
本文介绍了明智的元素串联多个列表(字符串列表的列表)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串列表,如下所示

i have a list of list of strings as below

lst = [['a','b','c'],['@','$','#'],['1','2','3']]

我想明智地将list元素内的每个字符串连接起来,预期输出如下:

I want to concatenate each string inside the lists element wise, expected output as below:

['a@1','b$2','c#3']

lst的大小可以变化.有什么方法可以完成此操作而无需进行for循环.
我尝试使用地图,但无法正常工作.

The size of lst can vary. is there any way to accomplish this without going through for loops.
I tried to use map, but its not working.

map(str.__add__,(x for x in list))

请帮助.

推荐答案

这是压缩子列表并使用''.join生成的元组进行映射的一种方法:

Here's one way zipping the sublists and mapping with ''.join the resulting tuples:

list(map(''.join, zip(*lst)))
# ['a@1', 'b$2', 'c#3']


zip 中,如docs聚合元素所示从几个可迭代对象.通过添加*,我们将解压缩列表,这意味着该函数将改为接收zip(['a','b','c'],['@','$','#'],['1','2','3']).


Here zip as shown in the docs aggregates elements from several iterables. By adding *, we are unpacking the list, which means that the function will instead be receiving zip(['a','b','c'],['@','$','#'],['1','2','3']).

现在,在每次迭代中,将应用 map ''.join到每个聚合的可迭代对象,即每个子列表中的第一个元素,然后是第二个,依此类推.

Now at each iteration, map will be applying ''.join to each of the aggregated iterables, i.e to the first element in each sublist, then the second, and so on.

这篇关于明智的元素串联多个列表(字符串列表的列表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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