python - 如何连接列表中的项目?

标签 python

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

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."]

最佳答案

循环列表项,构建字符串。每当当前项以句点结束时,将当前构建的字符串附加到最终结果,并开始构建新的字符串:

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.']

关于python - 如何连接列表中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65594885/

相关文章:

python - Pandas 数据框两列的交集

python - 在Python asyncio中创建并发任务之间的依赖关系

Python multiprocessing - 观察一个进程并在失败时重新启动它

python - 平滑速度更快的等效函数

python - 为列表中的每个项目分配特定的 ID,并生成具有重复 ID 的新列表

python - Mayavi:绕y轴旋转

python - 如何在 Python Django 中从表单实例创建表单集

python - 生成器比列表理解慢

python - Othello Alpha-Beta Pruning 玩得很厉害 python

python - 在 python 中将过滤器应用于 Google Analytics API