Skip to main content
 首页 » 编程设计

python之如果元素包含,则将 2 个元素合并在一起

2025年05月04日20xxx_UU

我有一个非常困惑的数据,我注意到元素的末尾有 '\n' 的模式,在此之前它需要与单个元素合并。

示例列表:

ls = ['hello','world \n','my name','is john \n','How are you?','I am \n doing well'] 
ls 

返回/试用:

print([s for s in ls if "\n" in s[-1]]) 
>>>    ['world \n', 'is john \n'] # gave elements that ends with \n 

如何让以 '\n' 结尾的元素与元素前的 1 合并?寻找这样的输出:

['hello world \n', 'my name is john \n', 'How are you?','I am \n doing well'] 

请您参考如下方法:

如果您正在减少一个列表,也许,一种可读的方法是使用reduce功能。

functools.reduce(func, iter, [initial_value]) cumulatively performs an operation on all the iterable’s elements and, therefore, can’t be applied to infinite iterables.

首先,你需要一种积累结果的方法,我使用了一个包含两个元素的元组:buffer with concatenated strings until I find "\n" 和列表结果。请参见初始结构 (1)。

ls = ['hello','world \n','my name','is john \n','How are you?','I am \n doing well'] 
 
def combine(x,y): 
    if y.endswith('\n'): 
        return ( "", x[1]+[x[0]+" "+y] )  #<-- buffer to list 
    else: 
        return ( x[0]+" "+y, x[1] )       #<-- on buffer 
 
t=reduce( combine, ls, ("",[]) ) #<-- see initial struct (1) 
t[1]+[t[0]] if t[0] else t[1] #<-- add buffer if not empty 

结果:

['hello world \n', 'my name is john \n', 'How are you? ', 'I am \n doing well '] 

(1) 解释了初始结构:你使用一个元组来存储缓冲区字符串直到 \n 和一个已经煮熟的字符串列表:

("",[])  

意思是:

("__ buffer string not yet added to list __", [ __result list ___ ] )