在python中顺序连接字符串

时间:2019-02-28 12:22:35

标签: python list concatenation

我需要顺序连接列表中的字符串,以将由换行符分隔的单词的两个部分连接起来。有人可以帮我吗?

list = ["a", "b", "c", "d"]

必填输出:

"ab"
"cd"   

8 个答案:

答案 0 :(得分:2)

假设您要加入成对的连续项目:

>>> lst = ['a', 'b', 'c', 'd']
>>> list(map(''.join, zip(*([iter(lst)]*2))))
['ab', 'cd']

在这里,zip(*([iter(lst)]*2))是通过zip列出列表中同一迭代器的两个实例来实现的成对元素,但是还有许多其他方法可以实现相同目的。

(注意:为了不遮盖内置类型,将list重命名为lst

答案 1 :(得分:2)

for i in range(0, len(l), 2):
    ''.join(l[i:i + 2])

答案 2 :(得分: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))]

答案 3 :(得分:1)

给出列表,

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')

答案 4 :(得分:0)

很抱歉,我大部分时间都使用numpy。因此,解决方案可以是:

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')

答案 5 :(得分:0)

您可以定义一个将列表中的元素分组的方法:

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

答案 6 :(得分:0)

您还可以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']

答案 7 :(得分:0)

您可以将列表切成偶数和奇数元素。

假设您的列表名为CREATE TABLE `T` (F text other null );

即使是元素-l

奇数元素-l[::2]

然后,您可以在压缩后使用列表推导将它们连接起来。所以:

l[1::2]