[英]concatenate strings sequentially in python
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. 此处, zip(*([iter(lst)]*2))
是通过将列表中同一迭代器的两个实例zip
来实现的元素对通用配方,但是还有许多其他方法可以做到这一点。
(Note: Renamed list
to lst
for not shadowing the builtin type) (注意:将list
重命名为lst
以便不影响内置类型)
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 在即将面世的Python 3.8(ETA秋季2019)中,可以更简洁地写成(我相信)为
[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) (请注意,不要劫持变量名称的关键字list
)
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')
使用rstrip
删除右边的字符,例如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: 或者,您可以按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
: 您也可以starmap
压缩列表的starmap
到操作员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
假设您的清单叫做l
Even elements - l[::2]
偶数元素l[::2]
Odd elements - l[1::2]
奇数元素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])]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.