I need to concatenate strings in a list sequentially to join the two parts of words that were separated by line breaks. Can someone help me?
list = ["a", "b", "c", "d"]
Required output:
"ab"
"cd"
I need to concatenate strings in a list sequentially to join the two parts of words that were separated by line breaks. Can someone help me?
list = ["a", "b", "c", "d"]
Required output:
"ab"
"cd"
Assuming you want to join pairs of consecutive items:
>>> lst = ['a', 'b', 'c', 'd']
>>> list(map(''.join, zip(*([iter(lst)]*2))))
['ab', 'cd']
Here, zip(*([iter(lst)]*2)) is a common recipe for pairs of elements by ziping two instances of the same iterator on the list, but there are many other ways to do the same.
(Note: Renamed list to lst for not shadowing the builtin type)
for i in range(0, len(l), 2):
''.join(l[i:i + 2])
Using a shared iterator,
>>> [x + next(itr) for itr in [iter(lst)] for x in itr]
['ab', 'cd']
In the forthcoming Python 3.8 (ETA fall 2019), that can be more succinctly written (I believe) as
[x + next(itr) for x in (itr:=iter(lst))]
for x in (iter(lst) as itr), reusing as from import, with and except instead of introducing new :=?as was eventually rejected to avoid adding another set of slightly different semantics on top of what existing uses of as already defined. See PEP 572 for all the gory details.You could define a method which groups for you the elements in the list:
def group_by(iterable, n = 2):
if len(iterable)%n != 0: raise Exception("Error: uneven grouping")
# if n < 2: n = 1
i, size = 0, len(iterable)
while i < size-n+1:
yield iterable[i:i+n]
i += n
So for example if your list is:
words = ["a", "b", "c", "d"]
group_by(words, 2) #=> [['a', 'b'], ['c', 'd']]
Or you can group by 3:
words = ["a", "b", "c", "d", "e", "f"]
cons = group_by(words, 3) #=> [['a', 'b', 'c'], ['d', 'e', 'f']]
Then you can use in this way:
res = [ "".join(pair) for pair in group_by(words, 2) ] # maybe you want to add "\n" to the joined string
#=> ['ab', 'cd', 'ef']
words = ["a", "b", "c", "d", "e"]
cons = group_by(words, 2) #=> Exception: Error: uneven grouping