簡體   English   中英

在python中順序連接字符串

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM