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.']
推荐阅读
- jwt - 如何在 FusionAuth 中生成签名和加密的 JWT 访问令牌
- kubernetes - 推出/重新启动我的应用程序时,kubernetes 服务是否可以更改 IP
- laravel - 当尝试运行 npm install 时显示此错误
- ios - 如何在 WebKit 中打开外部 URL?
- ruby-on-rails - 如何在 Rails 中的 ActiveRecord::Result 中对单个列(带有值)进行切片?
- python - 这个 Python 生成器示例到底是如何工作的?
- php - 'vcruntime140.dll' 14.0 与链接到 14.16 的 PHP 版本不兼容
- laravel - html选择选项的雄辩价值没有到达控制器对页面进行排序
- node.js - 如何在 ssh-exec 中使用 await/async?
- linux - 我们必须在哪里放置 linux 命令?