Python 如果两个元素包含

Python 如果两个元素包含,python,python-3.x,Python,Python 3.x,我有一个非常混乱的数据,我注意到在元素的结尾有“\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 tha

我有一个非常混乱的数据,我注意到在元素的结尾有“\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”结尾的it元素在元素之前与1合并?正在查找如下输出:

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

我写了这篇文章,所以它很容易理解,而不是试图把它作为一个列表理解变得更复杂

这将适用于任意数量的单词,直到您点击一个
\n
字符并清除其余的输入

ls_out=[]#您的传出ls
out=''#保留你的话语
对于范围(0,len(ls))中的i:
如果ls[i]中有“\n”:#检查结尾词,如果是,将其添加到输出并重置
out+=ls[i]
ls_out.append(out)
out=“”
else:#否则添加到当前单词列表中
out+=ls[i]
if out:#如果总ls不以结尾,请检查是否有剩余的单词in out\n
ls_out.append(out)
当字符串连接时,您可能需要添加空格,但我猜这仅适用于您的示例。如果是,请进行以下编辑:

out+=''+ls[i]
编辑:
如果您只想获取之前的一个,而不想获取之前的多个,可以执行以下操作:

ls_out=[]
对于范围(0,len(ls))中的i:
如果ls[i].endswith('\n'):#仅检查结尾
如果不是ls[i-1].endswith('\n'):#检查前面的字符串
out=ls[i-1]+“”+ls[i]#连接在一起
其他:
out=ls[i]#这个有,以前没有
elif ls[i+1].endswith('\n'):#下一个将获取此文件,因此跳过
持续
其他:
out=ls[i]#下一个不会这样添加这个
ls_out.append(out)

我写了这篇文章,因此它很容易理解,而不是试图让它作为一个列表理解变得更复杂

这将适用于任意数量的单词,直到您点击一个
\n
字符并清除其余的输入

ls_out=[]#您的传出ls
out=''#保留你的话语
对于范围(0,len(ls))中的i:
如果ls[i]中有“\n”:#检查结尾词,如果是,将其添加到输出并重置
out+=ls[i]
ls_out.append(out)
out=“”
else:#否则添加到当前单词列表中
out+=ls[i]
if out:#如果总ls不以结尾,请检查是否有剩余的单词in out\n
ls_out.append(out)
当字符串连接时,您可能需要添加空格,但我猜这仅适用于您的示例。如果是,请进行以下编辑:

out+=''+ls[i]
编辑:
如果您只想获取之前的一个,而不想获取之前的多个,可以执行以下操作:

ls_out=[]
对于范围(0,len(ls))中的i:
如果ls[i].endswith('\n'):#仅检查结尾
如果不是ls[i-1].endswith('\n'):#检查前面的字符串
out=ls[i-1]+“”+ls[i]#连接在一起
其他:
out=ls[i]#这个有,以前没有
elif ls[i+1].endswith('\n'):#下一个将获取此文件,因此跳过
持续
其他:
out=ls[i]#下一个不会这样添加这个
ls_out.append(out)

假设第一个元素不是以
\n
结尾,并且所有单词都超过2个字符:

res = []
for el in ls:
  if el[-2:] == "\n":
    res[-1] = res[-1] + el
  else:
    res.append(el)

假设第一个元素不是以
\n
结尾,并且所有单词都超过2个字符:

res = []
for el in ls:
  if el[-2:] == "\n":
    res[-1] = res[-1] + el
  else:
    res.append(el)
试试这个:

lst=[]
for i in range(len(ls)):
    if "\n" in ls[i][-1]:
        lst.append((ls[i-1] + ' ' + ls[i]))
        lst.remove(ls[i-1])
    else:
        lst.append(ls[i])
lst
结果:

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

lst=[]
for i in range(len(ls)):
    if "\n" in ls[i][-1]:
        lst.append((ls[i-1] + ' ' + ls[i]))
        lst.remove(ls[i-1])
    else:
        lst.append(ls[i])
lst
结果:

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

如果要减少列表,一种可读的方法就是使用函数

reduce(func,iter,[initial_value])对所有iterable元素累积执行操作,因此不能应用于无限iterable

首先,您需要一种stroke来累积结果,我使用一个包含两个元素的元组:缓冲区和串联字符串,直到找到“\n”结果列表。参见初始结构(1)

(1) 解释初始结构:使用元组存储缓冲区字符串,直到
\n
和一个已处理字符串列表:

("",[]) 
指:

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

如果要减少列表,一种可读的方法就是使用函数

reduce(func,iter,[initial_value])对所有iterable元素累积执行操作,因此不能应用于无限iterable

首先,您需要一种stroke来累积结果,我使用一个包含两个元素的元组:缓冲区和串联字符串,直到找到“\n”结果列表。参见初始结构(1)

(1) 解释初始结构:使用元组存储缓冲区字符串,直到
\n
和一个已处理字符串列表:

("",[]) 
指:

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

您可以使用“re”模块使用正则表达式求解它

import re
ls = ['hello','world \n','my name','is john \n','How are you?','I am \n doing well']
new_ls = []
for i in range(len(ls)):
    concat_word = ''                # reset the concat word to ''
    if re.search(r"\n$", str(ls[i])):      # matching the \n at the end of the word
        try:
            concat_word = str(ls[i-1]) + ' ' + str(ls[i])  # appending to the previous word
        except:
            concat_word = str(ls[i])     # in case if the first word in the list has \n
        new_ls.append(concat_word)
    elif re.search(r'\n',str(ls[i])):      # matching the \n anywhere in the word
        concat_word = str(ls[i])  
        new_ls.extend([str(ls[i-1]), concat_word])   # keeps the word before the "anywhere" match separate
print(new_ls)
这将返回输出

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

您可以使用“re”模块使用正则表达式求解它

import re
ls = ['hello','world \n','my name','is john \n','How are you?','I am \n doing well']
new_ls = []
for i in range(len(ls)):
    concat_word = ''                # reset the concat word to ''
    if re.search(r"\n$", str(ls[i])):      # matching the \n at the end of the word
        try:
            concat_word = str(ls[i-1]) + ' ' + str(ls[i])  # appending to the previous word
        except:
            concat_word = str(ls[i])     # in case if the first word in the list has \n
        new_ls.append(concat_word)
    elif re.search(r'\n',str(ls[i])):      # matching the \n anywhere in the word
        concat_word = str(ls[i])  
        new_ls.extend([str(ls[i-1]), concat_word])   # keeps the word before the "anywhere" match separate
print(new_ls)
这将返回输出

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

有些东西工作不正常,缺少一个元素:[“helloworld\n”,“我的名字是john\n”,“你好吗?我做得很好”]我在底部添加了一条评论。我假设在他们的示例文本中,它们没有外部空间,但在实际使用中,这些空间可能没有被剥离。如果正在剥离它们,可以更改字符串连接以添加空格。否。我的意思是你不能这样做:out+=ls[I]。。。它将包含元素3和4,因此您缺少结果中的一个元素。输出需要4个项目,而您只有3个项目。是的,正确,我解释说,除此之外,它是w