如何在同一索引处连接多个列表中的字符串
How to concatenate strings in multiple lists at the same index
我有3个series
,每个都是等长的,我把它们转换成3个list
。我想在同一索引处连接列表中的字符串,并将连接后的字符串放在另一个列表中。怎么做?例如list1[0] + list2[0] + list3[0]
每个索引 n
。
您可以使用 zip()
and a list comprehension:
>>> l1 = ["a", "b", "c"]
>>> l2 = ["1", "2", "3"]
>>> l3 = ["!", "?", "."]
>>> [''.join(item) for item in zip(l1, l2, l3)]
['a1!', 'b2?', 'c3.']
what if the l1, l2, l3 are in a list l, and I don't know how many elements in l, how to do the concatenation
在这种情况下,您可以 解压 带有子列表的列表到 zip()
函数参数:
>>> l = [l1, l2, l3]
>>> [''.join(item) for item in zip(*l)]
['a1!', 'b2?', 'c3.']
我有3个series
,每个都是等长的,我把它们转换成3个list
。我想在同一索引处连接列表中的字符串,并将连接后的字符串放在另一个列表中。怎么做?例如list1[0] + list2[0] + list3[0]
每个索引 n
。
您可以使用 zip()
and a list comprehension:
>>> l1 = ["a", "b", "c"]
>>> l2 = ["1", "2", "3"]
>>> l3 = ["!", "?", "."]
>>> [''.join(item) for item in zip(l1, l2, l3)]
['a1!', 'b2?', 'c3.']
what if the l1, l2, l3 are in a list l, and I don't know how many elements in l, how to do the concatenation
在这种情况下,您可以 解压 带有子列表的列表到 zip()
函数参数:
>>> l = [l1, l2, l3]
>>> [''.join(item) for item in zip(*l)]
['a1!', 'b2?', 'c3.']