I have 3 series
, each has equivalent length, I converted them to 3 list
. I want to concatenate the strings in the lists at the same index, and put the concatenated strings in another list. How to do that? e.g. list1[0] + list2[0] + list3[0]
for each index n
.
You can use 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
In this case, you can just unpack the list with sublist to the zip()
function arguments:
>>> l = [l1, l2, l3]
>>> [''.join(item) for item in zip(*l)]
['a1!', 'b2?', 'c3.']