python - Split and Append a list
问题描述
I have a list as follows:
['aaa > bbb', 'ccc > ddd', 'eee > ']
I am looking to split the list to get the following result, with an empty string element at the end
['aaa', 'bbb', 'ccc', 'ddd', 'eee','']
I tried the following code
for element in list:
list.append(element.split(' > '))
I am getting answer as follows:
[['aaa', 'bbb'], ['ccc', 'ddd'], ['eee','']]
After thinking I see that is what it supposed to work as. So how can I achieve what I am looking for.
解决方案
您可以使用列表理解:
l = ['aaa > bbb', 'ccc > ddd', 'eee > ']
[item.strip() for sublist in [element.split(">") for element in l] for item in sublist]
输出是:
['aaa', 'bbb', 'ccc', 'ddd', 'eee', '']
我承认这个列表理解不是超级容易理解,但它是单行的:)
推荐阅读
- javascript - 当测试和测试对象在不同文件中时,从其他文件模拟导入的函数
- azure-language-understanding - 如何使用 LUIS 短语列表来增强模式识别?
- javascript - 创建 React 组件数组?
- html - 如何使用 CSS 替换 PNG 图像的颜色?
- spring - 何时为 Spring Boot 执行指定多个配置文件
- excel - 过滤数据后获取单元格
- php - Yii2:如何发送模型和不属于模型的数组
- python - Weasyprint 或 Reportlab 用于在 Heroku 上生成 Django 报告
- linux - 如何使用 signalfd 在多线程 Linux 程序中捕获 SIGTERM
- reactjs - 如何有条件地运行 Apollo 客户端的 useSubscription 钩子?