[英]concatenate strings sequentially in python
我需要按顺序连接列表中的字符串,以将由换行符分隔的单词的两个部分连接起来。 有人能帮我吗?
list = ["a", "b", "c", "d"]
要求的输出:
"ab"
"cd"
假设您想加入成对的连续项目:
>>> lst = ['a', 'b', 'c', 'd']
>>> list(map(''.join, zip(*([iter(lst)]*2))))
['ab', 'cd']
此处, zip(*([iter(lst)]*2))
是通过将列表中同一迭代器的两个实例zip
来实现的元素对通用配方,但是还有许多其他方法可以做到这一点。
(注意:将list
重命名为lst
以便不影响内置类型)
for i in range(0, len(l), 2):
''.join(l[i:i + 2])
使用共享的迭代器,
>>> [x + next(itr) for itr in [iter(lst)] for x in itr]
['ab', 'cd']
在即将面世的Python 3.8(ETA秋季2019)中,可以更简洁地写成(我相信)为
[x + next(itr) for x in (itr:=iter(lst))]
给定一个清单,
L=['a', 'b', 'c', 'd']
(请注意,不要劫持变量名称的关键字list
)
您可以分两个步骤进行操作:
for i in range(0,len(L)-1,2):
print(L[i]+L[i+1])
使用rstrip
删除右边的字符,例如L[i].rstrip('\\n')
抱歉,我大部分时间都用麻木。 因此,解决方案可以是:
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')
您可以定义一个将列表中的元素分组的方法:
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
因此,例如,如果您的列表是:
words = ["a", "b", "c", "d"]
group_by(words, 2) #=> [['a', 'b'], ['c', 'd']]
或者,您可以按3分组:
words = ["a", "b", "c", "d", "e", "f"]
cons = group_by(words, 3) #=> [['a', 'b', 'c'], ['d', 'e', 'f']]
然后,您可以通过以下方式使用:
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
您也可以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']
您可以将列表切成偶数元素和奇数元素。
假设您的清单叫做l
偶数元素l[::2]
奇数元素l[1::2]
然后,您可以在压缩后使用列表推导将它们串联起来。 所以:
[x + y for x, y in zip(l[::2], l[1::2])]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.