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 zip
ing 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))]
Given a list,
L=['a', 'b', 'c', 'd']
(note, not hijacking the keyword list
for a variable name)
you can walk through this in steps of two:
for i in range(0,len(L)-1,2):
print(L[i]+L[i+1])
Use rstrip
to remove characters o the right, for example L[i].rstrip('\\n')
I'm sorry that I use most of the time numpy. So a solution can be:
li = ['a', 'b', 'c', 'd']
L = np.array(li)
a1 = np.char.array([L[0], L[2]])
a2 = np.char.array([L[1], L[3]])
a1 + a2
chararray(['ab', 'cd'], dtype='<U2')
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
You can also starmap
zipped lists to the operator concat
:
from operator import concat
from itertools import starmap
l = ["a", "b", "c", "d"]
z = zip(l[::2], l[1::2])
list(starmap(concat, z))
# ['ab', 'cd']
You could slice your list into the even elements and odd elements.
Let's say your list is called l
Even elements - l[::2]
Odd elements - l[1::2]
Then you could use a list comprehension to concatenate them after zipping. So:
[x + y for x, y in zip(l[::2], l[1::2])]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.