首页 > 解决方案 > 如何连接列表中的项目?

问题描述

如果列表的最后一个字符不是“。”,我想连接列表中的项目。

l=["First item","Second item","Third item.","Fourth item."]

abc=[element for element in l if not element[-1]=="."]

我尝试使用列表推导,但我不知道如何使用列表推导连接两个项目。

我想要的是:

abc=["First itemSecond itemThird item.","Fourth item."]

标签: python

解决方案


循环遍历您的列表项,构建字符串。每当当前项目以句点结尾时,将当前构建的字符串附加到最终结果中,然后开始构建新字符串:

l=["First item","Second item","Third item.","Fourth item."]

result = []
curr_str = ""
for item in l:
    curr_str += item
    if item[-1] == ".":
        result.append(curr_str)
        curr_str = ""

 ['First itemSecond itemThird item.', 'Fourth item.']

推荐阅读